In C and C++, Freeing a NULL pointer will result in nothing done.
Still, I see people saying that memory corruption can occur if you "free memory twice".
Is this true? What is going on under the hood when you free memory twice?
In C and C++, Freeing a NULL pointer will result in nothing done.
Still, I see people saying that memory corruption can occur if you "free memory twice".
Is this true? What is going on under the hood when you free memory twice?
So, after
free
ing the first time, you should dop = NULL
, so if (by any chance),free(p)
is called again, nothing will happen.Here is why freeing memory twice is undefined: Why free crashes when called twice
When you call free on a pointer, your pointer will not get set to NULL. The free space is only given back to a pool to be available for allocation again. Here an example to test:
This program outputs for me:
and you can see, that free did nothing to the pointer, but only told the system that the memory is available for reuse.
Freeing memory does not set the pointer to null. The pointer remains pointing to the memory it used to own, but which has now had ownership transferred back to the heap manager.
The heap manager may have since reallocated the memory your stale pointer is pointing to.
Freeing it again is not the same as saying
free(NULL)
, and will result in undefined behavior.To avoid free twice i alway using MACRO for free memory:
this macro set p = NULL to avoid dangling pointer.
Yes, "undefined behavior" which almost always results in a crash. (while "undefined behavior" by definition means "anything", various types of errors often behave in quite predictable ways. In case of free(), the behavior is invariably segfault or respective "memory protection error" characteristic to the OS.)
Same if you free() a pointer to anything else than NULL or something you malloc'd.
char x; char* p=&x; free(p);
// crash.This is undefined behavior, that can result in heap corruption or other severe consequences.
free()
for a null pointer simply checks the pointer value inside and returns. That check will not help against freeing a block twice.Here's what happens usually. The heap implementation gets the address and tries to "take ownership" of the block at that address by modifying its own service data. Depending on the heap implementation anything can happen. Maybe it works and nothing happens, maybe the service data is corrupted and you've got heap corruption.
So don't do it. It's undefined behavior. Whatever bad things can happen.