In your insert_nodeinsertNode
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. nowNow 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 = NULLcurrent = NULL
at the moment. No whenWhen you do current -> next = newNode
, you're de-referencing NULL, resulting in seg-fault.
So only modification would be
while(current !=NULL && current -> next != NULL) //Check whether the list is empty, if not fetchFetch 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