r/C_Programming • • 2h ago

Why is Double-Free undefined behavior?

I'm wondering what the reasoning is for leaving double-freeing of memory as undefined behavior? I've run into it on a project and I'm getting runtime errors reporting the double free. I suppose from where I'm sitting (with my very limited C experience), I would have expected that freeing memory that has previously been freed (and not since reallocated) would be a no-op.

Maybe I'm misunderstanding how memory allocation works. But in a very oversimplified way my understanding is that the pointers that free expects are the ones that correspond to the beginning of a dynamically allocated block of memory. And when one uses malloc (realloc or calloc), the allocator allocates the memory you need and gives you a pointer to the start of it. With that understanding I would have thought free could only have two outcomes. Either the pointer doesn't point to the start of an allocated block, and nothing happens. Or it does and the memory is freed.

Any insight would be greatly appreciated!

Also as an aside, does free only work with [m/c/re]alloc? Or can it free other allocators as well.

19 Upvotes

26 comments sorted by

View all comments

24

u/ir_dan 2h ago

Undefined behaviour is often for the sake of implementation freedom. Having the behaviour you suggest would place more responsibility on the implementation for no real benefit.

2

u/Classic_Department42 50m ago

Yes, the c standard is so to make it easy to make (efficient) compilers and efficient code. Probably not having to consider double free as a compiler maker helps witj both