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
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started