Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Management Databases And Organizations

Authors: Richard T. Watson

6th Edition

1943153035, 978-1943153039

More Books

Students also viewed these Databases questions