Can someone explain me why freeing a
twice in a row causes a crash, but freeing a
first, then b
, and then a
again does not crash?
I know that a free will insert the heap chunk in a double linked free list. Freeing twice would insert the same chunk twice in the free list. But why is the crash happening?
int *a = malloc(8); int *b = malloc(8); free(a); // free(a); // Would crash! free(b); free(a); // No crash.
Advertisement
Answer
Because in C lingo, undefined behavior is just that: undefined. Anything might happen.
Also see man 3 free
:
[…] if
free(ptr)
has already been called before, undefined behavior occurs.