user1234567 user1234567 - 1 month ago 4
C Question

How to insert a whole line into a node in c?

How to using getline() to get a whole line and insert it into linked list?
Here is my code. I am sure whether I can look a line as a whole string. When I tried only one line, the program is working with no problem. But when I tried to insert another line it shows me Segmentation fault: 11.

typedef struct Node{
struct Node *next;
char *data;
}Node;

void insert(Node **head, char *input){
Node *newNode = malloc(sizeof(Node));
newNode->data = input;
newNode->next = NULL;

Node *cur = *head;
if(*head == NULL){
*head = newNode;
}
else{
while(cur!=NULL){
cur = cur->next;
}
cur->next = newNode;
}
}

void Pint(Node *head){
Node *cur = head;
while(cur!=NULL){
printf("%s\n", cur->data);
cur = cur->next;
}
printf("\n");
}


int main(){
Node *head = NULL;
char *input = NULL;
size_t len = 0;
while(getline(&input, &len, stdin)!=EOF){
insert(&head, input);
input = NULL;
}
Pint(head);
return 0;
}



Answer

I believe the seg fault is when you do:

    while(cur!=NULL){
        cur = cur->next;
    }
    cur->next = newNode;

Since cur is NULL after the while loop, it doesn't have a next.

In the while loop, I would check when cur->next is not null, that way when you assign the newNode to cur->next, cur will not be NULL.

That would explain why the first one worked, since it just set *head = newNode, but then the seg fault occurs when you add the next one.