r/C_Programming • u/FernwehSmith • 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.
View all comments
1
u/tstanisl 2h ago
From practical point of view, between two free() calls someone else (other thread/library helper/etc) may allocate memory and get the pointer that was recently freed. Freeing it again will release memory that is actually in use. So now someone else can allocate this block again. Now you have two pieces of program, accessing and modifying the same memory, not knowing about one another. It will cause a havoc at the most unexpected time, often in non-deterministic way.
Of course, the true nature of UB is a lot more abstract and subtle, so tricks will not help, even if you think they will!
Don't fight UB, because you cannot win. Just don't trigger it.