Freeing the head node of linked list

c, linked-list, malloc, memory

Solution

Your linked list should be like:

head
+---+    +---+    +---+                               
| 1 |--->| 2 |--->| 3 |---+
+---+    +---+    +---+   |                                
                         null  

`head` node keeps address of fist node only, if you do `free(head)`, then it will free memory of first node with value `1` only and other-nodes are still in memory and its valid to access them, but you should first save address of node `2`, to access linked list (else you would have a memory leak in your code).

Do like:

   new_head = head->next;
   free(head);

Once you deallocate/free() a memory, its Undefined behavior to access that not (address becomes invalid).

From comment:

Yes, you need a loop to free() memory for all nodes in linked-list, do something like this:

 while(head){          // while head not null
     new_head = head->next;   // first save address of next
     free(head);           // free first node
     head = new_head;      // set head to next node, not yet free
 }

- comment-2: If you don't delete/free dynamically allocated memory in your program then it will remain allocated to your process till it not terminates (remember in C we don't have Garbage collector). Dynamically allocated memory has life till your program does't terminate. So if you have finished your work with allocated memory, free it explicitly.

Problem

If I free the head node of the linked list would it just remove the head node with other nodes still in memory or it would free the entire list and how ?

Original source