why does adding a linked list in code create a segmentation fault?

There is a problem here:

Node head = {k, list[j - 1]};
list[j - 1] = &head;

head is a local variable, which will go of scope (or in simple terms: it will be destroyed) as soon as the handle_input function returns.

In this line list[j - 1] = &head; you store the address of that local variable in the list array which points actually to an array provided in main.

You need to handle this differently by allocating memory:

Node *head = malloc(sizeof(*head));
head->succ = k;
head->next = list[j - 1]
list[j - 1] = head;

There may be other problems though, I didn’t check.

Don’t forget to free the allocated memory at some point in main.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top