简体   繁体   中英

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?

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.

They are not equivalent.

In C, if you explicitly allocated memory (eg, by using malloc ), you need to explicitly free it (by using free ).

If you just assign head = NULL , you won't be able to access the following elements in the linked list, but their memory will still be allocated - the process will still hold this memory, and you'll have a memory leak on your hand.

Because there is no garbage collector in C. This means you should collect your garbage yourself. Everything you allocated on the heap has to be deleted manually. Forgetting to do it is called memory leak .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM