Hello.
What are the implications of free() a pointer twice?
Code:.... gchar *string; .... string = strcat (....) free(string); free(string); .....
Hello.
What are the implications of free() a pointer twice?
Code:.... gchar *string; .... string = strcat (....) free(string); free(string); .....
Last edited by guillermoh; 02-07-2008 at 08:26 PM.
That's undefined behavior.
Just don't do it.
Also, don't free() a pointer which has not been malloc()'ed
I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo
Usually it goes boom!
because it is undefined behaviour - try-and-see approach is not very good in this case. Someone could be so unlucky that in his "tests" everithing will seem OK... And only after implementing this "works for me" code in the real project the long expected "boom" will occure
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
guillermoe, NULL free()'s argument so that subsequent calls don't matter.
Code:type * p = foo(); // presume foo allocates types // use p . . . free( p ); p = NULL; free( p ); // harmless
Yeah. Stray pointers are a problem regardless, though: that's not unique to malloc'd stuff. A pointed-to object could just as easily fall out of scope beforehand, and something's done with it. Whether that makes the advice bad, I'm not ready to say.
As to exactly what happens when you free twice, it is very much dependent on the implementation of free(). A very likely scenario is that it will stick the same memory block twice in the list of free memory blocks - which means the first and second malloc with a matching size, it will return the same pointer.
Another option is that free actually realizes and gives an error message.
A further possibility is that the free causes an infinite loop in a linked list of free memory blocks, because the second free causes the block to point to itself, and next time you do a malloc of a bigger block of memory, malloc() tries to walk the list and gets stuck in an endless loop.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.