Question: This is done in C++. I run into a segmentation fault when I try and run the program. When I run the program and enter

This is done in C++. I run into a segmentation fault when I try and run the program. When I run the program and enter in 1 2 3 4, the correct output should be [{1}, {2}, {3},{4}], but ends up segmentation faulting. If anyone could provide an explanation as to why this is occurring and modify the code to produce the correct output. To compile the code you must use -lreadline when compiling.

#include #include #include #include #include #include #include #include

using namespace std;

struct Node{ char* data; Node *next; }; struct Node *head = NULL; int length = 0;

void addNode(char* data){ Node* newnode = (struct Node*) malloc(sizeof(struct Node)); newnode->data = data; Node* temp = head; if(head != NULL){ while(temp->next != NULL) temp = temp -> next; temp-> next = newnode; } else head = newnode; length++; } void print(){ Node* temp = head; while(temp != NULL){ cout << "{" << temp->data << "}"; temp = temp->next; } }

int main(){ static char* line_input = readline("> "); char* tok = strtok(line_input, " "); while(tok != NULL){ addNode(tok); tok = strtok(NULL, " "); } cout << "["; print(); cout << "]"; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!