1. Engineering
  2. Computer Science
  3. this is done in c i run into a segmentation...

Question: this is done in c i run into a segmentation...

Question details

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 <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <ctype.h>
#include <malloc.h>
#include <readline/readline.h>
#include <readline/history.h>

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 << "]";
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution