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, you get undefined behavior, and anything could happen.
1) Handling of dynamic memory is not done by compiler. There are run-time libraries which take care of this. For eg. : glibc provides APIs like malloc and free, which internally make system calls(sys_brk) to handle the heap area.
2) Freeing same memory twice refers to a condition like this : Suppose you have char *cptr;
You allocate memory using : cptr = (char *) malloc (SIZE);
Now, when you no longer need this memory, you can free it using this : free(cptr);
Now here what happens is the memory pointed to by cptr is free for use.
Suppose at a later point of time in the program you again call a free(cptr), then this is not a valid condition. This scenario where you are freeing the same memory twice is know as "freeing a memory twice" problem.`
Freeing memory more than once can have bad consequences. You can run this piece of code to see what may happen for your computer.
Many standard libraries like CSparse use a wrapper function that handles memory issues. I copied the function here:
This function can handle the issues with memory. Please note that you have to take care of the condition that malloc returns NULL in some cases