Possible Duplicate:
Should one really set pointers toNULL
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...
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With