I have a very large code with malloc's, free's, loop's etc. Sometimes, takes to long for me to figure out where is the problem since I receive the error in one part of the program, but what is really causing the problem is something far away in code. Most of the problems is caused by double free that I hadn't noticed. But some of them works fine for a time and then it crashes.
So, consider an example that works most of times:
int main() {
char *x = (char*) malloc(10);
char *y = (char*) malloc(10);
free(x);
free(y);
x = (char*) malloc(10);
free(y); // Am I lucky?
return 0;
}
Why do I don't receive an error when running the second free(y)? I checked that the pointer of x after the second malloc is equal to the previous allocated address of y. It's not always that it works. Sometimes it crashes.
So, my question is: Is there any way to force the error when trying to do a double free?
Thanks!
After the free(), set the pointer to null to avoid "freeing" the same address.
Free() does not change the value of the pointer, thus, the address could be reused by the program to alloc new blocks.
Free(null) does nothing and will not break your code.
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