Skip to main content
2 of 2
added 157 characters in body
C--
  • 306
  • 1
  • 11

In your insertNode function, while your iterating to find the last node, you should check whether the next_node is NULL, not current_node is NULL.

Let's say, we had two nodes

  1   ->   2   ->   NULL
head

When you start iterating, using

while(current != NULL) 
   current = current -> next;

It will eventually reach the node 2. Now this is the last node, you should stop here, but according to your while loop(current != NULL), it will move onto NULL and then break out of the loop.

So current = NULL at the moment. When you do current -> next = newNode, you're de-referencing NULL, resulting in seg-fault.

So only modification would be

while(current -> next != NULL) //Fetch me the last node

But there is till one important thing to do. You're not checking whether list is empty or not inside insertNode function.

if (head == NULL) {
    node_t *newNode = getNode(val);
    head = newNode;
    return;
}

Edit: Looks like you're assigning a node to head inside main function. The above check is not necessary

C--
  • 306
  • 1
  • 11