Fee
Fee

Reputation: 861

Double Free - crash or no crash

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.

Upvotes: 0

Views: 1187

Answers (1)

Jens
Jens

Reputation: 72697

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.

Upvotes: 7

Related Questions