Search code examples
clinked-listfreesingly-linked-list

Can't I directly put head=NULL if i want to destroy linked list and free memory?


Why do we need free()? Putting the head node as NULL does similar work, doesn't it?


Solution

  • Why do we need free()?

    The function free is used to free a dynamically allocated memory.

    Putting the head node as NULL does similar work, doesn't it?

    Putting NULL in the pointer to the head node does not free all dynamically allocated memory in the list neither for the head node nor for other nodes. This leads to loosing the address of the first dynamically allocated node and as a result you will get numerous memory leaks because the memory becomes inaccessible (but not freed)..

    Consider the following demonstrative program.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) 
    {
        int *p1 = malloc( sizeof( int ) );
        
        *p1 = 10;
        
        printf( "*p1 = %d\n", *p1 );
        
        int *p2 = p1;
        
        p1 = NULL;
        
        printf( "*p2 = %d\n", *p2 );
        
        free( p2 );
        
        return 0;
    }
    

    Its output is

    *p1 = 10
    *p2 = 10
    

    In the program there is dynamically allocated a memory for an object of the type int and the address of the allocated memory was assigned to the pointer p1.

    After assigning NULL to the pointer p1 the address of the allocated memory is not stored in this pointer any more.

    So if the address was not assigned to the second pointer p2 then the address of the allocated memory would be lost forever and we could not free the memory.

    Only due to having a copy of the address in the pointer p2 we can free the allocated memory.

    Thus setting a pointer to NULL only changes the value stored in the pointer. The allocated memory is not touched in any way.