Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we nullify pointer after freeing memory by free()? [duplicate]

Tags:

c

null

pointers

Possible Duplicate:
Should one really set pointers to NULL after freeing them?

I have allocated dynamic memory to pointer using malloc and calloc. After using this pointer, I should free the memory so that block can be returned to OS(its fine). Now My question is that after freeing the block, why should I do something like that:

pointer = NULL;

Thanks for help...

like image 785
Sandeep Pathak Avatar asked Feb 01 '11 10:02

Sandeep Pathak


People also ask

Should you set a pointer to NULL after freeing it?

Dangling pointers can lead to exploitable double-free and access-freed-memory vulnerabilities. A simple yet effective way to eliminate dangling pointers and avoid many memory-related vulnerabilities is to set pointers to NULL after they are freed or to set them to another valid object.

What happens to pointer after free?

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. It will not automatically be changed to NULL or anything else.

What happens if you free a pointer twice in C?

If we free the same pointer two or more time, then the behavior is undefined. So, if we free the same pointer which is freed already, the program will stop its execution.

What happens when we free a pointer in C?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.


1 Answers

So that we don't leave dangling pointers behind. Without nulling out unused pointers, you have no way to detect later whether the pointer can be safely dereferenced or freed. And attempting to dereference or free a dangling pointer results in undefined behaviour ( = crash).

like image 120
Péter Török Avatar answered Sep 27 '22 23:09

Péter Török