c - Freeing the head node of linked list -


if free head node of linked list remove head node other nodes still in memory or free entire list , how ?

your linked list should like:

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

head node keeps address of fist node only, if free(head), free memory of first node value 1 only , other-nodes still in memory , valid access them, should first save address of node 2, access linked list (else have memory leak in code).

do like:

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

once deallocate/free() memory, undefined behavior access not (address becomes invalid).

from comment:

  1. yes, need loop free() memory nodes in linked-list, 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 next node, not yet free  } 
  2. comment-2:
    if don't delete/free dynamically allocated memory in program remain allocated process till not terminates (remember in c don't have garbage collector). dynamically allocated memory has life till program does't terminate. if have finished work allocated memory, free explicitly.

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -