Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always a good practice to set pointers to NULL after free()-ing them? [duplicate]

Tags:

c

null

memory

free

Possible Duplicate:
Setting variable to NULL after free …

I am learning about good C programming practices and my friend told me to always set the pointers to NULL after free()ing them (or calling a specific freeing function).

For example:

char* ptr = malloc(100);
...
free(ptr);
ptr = NULL;

or

struct graph* graph = create_graph();
...
destroy_graph(graph);
graph = NULL;

Why is this a good practice?

Update: After reading the answers, it seems an awful practice to me! I am hiding possible double-free() errors. How can this possibly be a good practice? I am shocked.

Thanks, Boda Cydo.

like image 556
bodacydo Avatar asked Jul 29 '10 18:07

bodacydo


People also ask

Should you set pointer to NULL after free?

After using free(ptr) , it's always advisable to nullify the pointer variable by declaring again to NULL. e.g.: free(ptr); ptr = NULL; If not re-declared to NULL, the pointer variable still keeps on pointing to the same address (0x1000), this pointer variable is called a dangling pointer.

Should you set pointers to NULL?

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.

Can you use a pointer after you free it?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address.


1 Answers

While it can't hurt, it doesn't always help. The issue to consider is that it's easy for there to be multiple copies of the pointer and most likely you are only going to set a single one to NULL. The classic example of where it doesn't help at all is:

void free_graph(graph *g)
{
    ...
    free(g);
    g = NULL;  // not useful in this context
}

The problem here is that you are only setting the pointer that is local to free_graph to NULL and the pointer is held by the caller of free_graph will still have it's original value.

like image 181
R Samuel Klatchko Avatar answered Sep 28 '22 10:09

R Samuel Klatchko