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?
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