Freeing memory twice

Vijay picture Vijay · Mar 18, 2010 · Viewed 14.5k times · Source

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?

Answer

N 1.1 picture N 1.1 · Mar 18, 2010
int *p = malloc(sizeof(int));
//value of p is now lets say 0x12345678

*p = 2;
free(p); //memory pointer is freed, but still value of p is 0x12345678
         //now, if you free again, you get a crash or undefined behavior.

So, after free ing the first time, you should do p = 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