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.

16 Upvotes

26 comments sorted by

20

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.

→ More replies (1)

12

u/ralphpotato 2h ago

Most of the time when these kinds of things are undefined behavior it’s so that the implementation isn’t constrained any more than it needs to to fulfill the contract. There are a lot of ways a memory allocator can work, and C basically wants to allow for as little overhead as possible regarding bookkeeping.

In most implementations, it’s likely that there’s enough bookkeeping on the allocator side that a double free is probably a no-op, in the same way that a lot of the times memory you’re given is already zeroed out even if it wasn’t specifically guaranteed. But forcing the allocator to ensure that a double free is a no-op could constrain some implementations, especially on some of the weird platforms that C was meant to accommodate.

In general it just goes with the overall C philosophy to do less bookkeeping by default and let the caller keep track of what it needs to. Double freeing is likely a logic bug in most programs anyway. If you’re writing something where you intend to allow for this, free(NULL) is explicitly a no-op for this purpose. If your program has 2 pointers to the same location and they both at some point call free() it almost certainly means these parts of the program weren’t aware who owned the lifetime of that memory and that’s very bad.

8

u/chkno 2h ago edited 2h ago

After the first free, that area of memory can be allocated to something else. Suppose it is reallocated. Now you come along with the second free of your double-free. Now you've freed something that's still in use elsewhere. Uh oh.

One could, of course, write an allocator that could handle this. But that would require extra book-keeping (for example, Fil-C does this), and that extra book-keeping comes with a significant performance penalty. So we promise that our programs will free only once and we get fast execution in exchange for this promise.

8

u/zhivago 2h ago

So that it doesn't need to keep track of what has been free'd.

Which you could also do by searching what has been allocated and seeing if it's not there.

Or which you could do by making it someone else's problem.

Making it someone else's problem is much cheaper.

6

u/FedUp233 2h ago

One thing, how do you know it hasn’t been re-allocated? You have no idea where the heap might allocate any new request. And would it be better if it was ok if that block not reallocated but an error if it happened to be? Talk about random errors!

And remember, when the heap allocates a chunk of memory, it keeps size information at the start (and gives you a pointer just beyond that). If a pointer points anywhere but to the start of an allocated block, in many systems it has no way to even know if it’s been allocated!

And if you’re doing defensive programming, you should be setting the pointer null when you free it, or gives y pointer that you are no longer using. I know you’re talking c, not c++, but think along the lines of c++ smart pointers like unique pointer or shared pointer.

And finally, if you’re double freeing something, it points to a serious logic problem in your code. You should never have a case come up where you try to free something twice. It shows you aren’t in proper control of the lifetimes of your data.

4

u/master-o-stall 2h ago

This thread discusses double-free and why is it even problematic: https://www.reddit.com/r/C_Programming/s/NvzaftxQeB

2

u/bothunter 2h ago

The problem is that memory could be reused by another part of the program in the time between the first free and the second free.  Which means the program just freed memory to a pointer it didn't control.  Now the other pointer is being used after it has been freed.  This will work at first, but you've started corrupting the heap in a way that is going to eventually cause a crash.  And that crash is going to be in a very different part of the program and is going to be very difficult to debug.

→ More replies (1)

2

u/ouyawei 1h ago

How would you know it's been previously freed?

The memory could be used again in the meantime.

2

u/ern0plus4 1h ago edited 1h ago

UB is a wrong term.

Say, you have a struct, say, type of Elephant. It contains heigjt, weight, name etc. You allocate one, fill with valud data, then accidentally cast it to Zebra.

It's UB.

But if they have exact same fields, you'll don't even notice. If height is u16 for one, i16 for another, it never occurs a problem. If you change weight and height order... if one measures in inches, other in meters... m vs cm... field order and size change...  And you can think any variation... that's it's why UB. There's no simple rule how it will go wrong, if ever.

2

u/Cathierino 1h ago

C doesn't even guarantee that your two structs will match after compilation even if they have the same fields in the same order.

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.

1

u/renshyle 2h ago

In addition to what others said, there's also the problem of reallocation. The pointer you freed could have been allocated elsewhere by the time you free it again. There's no way to differentiate the old and new pointers so it would free the new allocation

1

u/stevevdvkpe 2h ago

Calling free() on a previously-freed allocation has unpredictable results, as well as bad implications for what the program is doing. You could be calling free() on a region that was already freed, which might be a no-op or might result in memory corruption as the second free() tries to operate on allocation tracking data that is no longer valid for that region. You could be calling free() on a region that another part of the program intends to use later, but won't know has been freed already. free() on a valid allocation puts that region back into the pool of free memory so that region might already have been reallocated to something else, and if you were trying to access data in that region thinking it was still allocated to you before freeing it, the data you were expecting to find there might have been overwritten with something else.

It's undefined behavior because you simply can't know which of these situations is happening at the time of the second free(), and often your program preceded that call with operations on the region of memory it thinks is still allocated which are also likely to have unpredictable or invalid results.

malloc() and realloc() use specific data structures and conventions for tracking regions of allocated memory so free() has to operate on those same data structures and follow the same conventions to keep the heap in a consistent state and properly distinguish used and free regions of the heap. free() used on a pointer to a memory region managed by different allocation functions using different data structures and conventions will also have unpredictable results.

1

u/RealisticDuck1957 2h ago

One problem dealing with a double free() is that a freed allocation may be reused. Essentially impossible to prevent in threaded code within normal C memory management. And possible in a sloppy single thread that does a free(), malloc(), then a second free of the same address.

1

u/Due-Mortgage-6854 2h ago

because C prioritizes speed over keeping a slow master list of valid pointers. freed memory holds allocator metadata, so a second free() corrupts it

1

u/CounterSilly3999 1h ago

May be it's because the list of references to allocated regions is kept together with them -- as additional entries prepending the addres being allocated, for example. Random address has garbage at these locations.

1

u/Big-Rub9545 1h ago

C punishes bad programming practices. Severely.

1

u/irqlnotdispatchlevel 1h ago

Making a double free a no op sometimes just makes it harder to catch and debug. You can't always make it a no op. Same for checking if the freed pointer points to the start of an already allocated block. You will, every now and then, be in this exact situation. Not to mention that if you get to this point you already have an issue in your code, so all you're doing is hiding it.

1

u/Cathierino 1h ago

Depending on how the heap allocation is implemented, there might be no way for the runtime allocator to catch a double free and trying to access invalid allocation bookkeeping data. If the pointer doesn't point to a valid block, it will interpret the data around it in a way that can corrupt your heap or even crash your program.

If you allow double free at the standard level, you are also restricting what kind of allocator implementations can be used by the compiler.

1

u/cdb_11 1h ago

Making double-free a no-op only works if free was a no-op in the first place, and you never reuse memory.

Addresses are not unique, they are reused. Even in the best case scenario where the allocator can only handle fixed allocation sizes, once you free the memory it can be reused immediately. There can be some completely different object of a completely different type living there now, and you can't tell the difference. All the allocator can do is free it anyway, because it can't tell the difference either, and the code that was managing that new object isn't going to expect that, even if it wanted to. If you wanted to be malicious, you could then allocate again, reuse that address and place some malicious data there, that would steer the program into doing something unintended or harmful.

In practice it's worse than that, because malloc has to handle dynamic allocation sizes. So often implementations will put extra bookkeeping data right before and after allocated memory. The exact locations of that bookkeeping data will shift around as you allocate and deallocate memory of different sizes. Bugs like double-frees, use-after-frees or out-of-bound writes can corrupt that entire data structure.

It is possible to design an allocator where double-free is a no-op, but it's not going to be compatible with malloc or the current ABIs. You either have to put extra unique allocation IDs inside every pointer, or add a GC to the language that can scan all existing pointers.

1

u/earwiggo 1h ago

Undefined behaviour also allows for technologies like AMD's MTE to detect the problem and signal the process or something.

1

u/_yrlf 1h ago edited 58m ago

The main reason for it is probably to allow the implementation to a) not need to keep records of already free'd objects, and b) allow it to flag such erroneous frees or abort. If initially, you had a double free in Task A, but the memory was not reused in between, then with your proposal of allowing double frees as a NOP would mean this silently works, and you would not notice.

If later, in a future version of the application, a new Task B was added that reuses the same memory that Task A had allocated before it is double-freed, you now have a problem: Task A accidently deallocates something Task B still needs (causing Task B to then trigger a use-after-free and likely crash), and because the original code in Task A was "working fine" before, you might not even have the idea to check that the problem is there, and would probably look for a bug in the Task B code that isn't there.

If double free is undefined behaviour, the implementation is allowed to catch this and abort the program in the first case already, saving you from time-consuming debugging.

Of course this is a tradeoff: In many cases, malloc implementations will not have a check for double free because of performance reasons, so in real code you might still run into the situation that a heap UAF/double-free in a component is causing a crash in an unrelated component.

EDIT: One could also make an argument for simplicity of specification: If double free is defined as UB, the specification does not have to define what happens with the memory after it's freed, and it does not have to talk about what could happen in other components in between and how that affects the validity of your call to free().

1

u/gremolata 40m ago

the pointers that free expects are the ones that correspond to the beginning of a dynamically allocated block of memory

Correct, but actually checking for that is expensive, so many allocators simply assume that the pointer passed to free is a valid one. This assumption can mess up internal allocator's state when it doesn't hold ... which is the case with double free.

1

u/Conscious_Support176 8m ago

Because if you want free to do nothing when given an address that was previously freed, it will need to recognise that address. So what you’re actually asking is that the free operation doesn’t simply free the memory, but does something like half-free the memory so that it can do a no op if you give the same address again.

Address sanitisation tools do this kind of thing to help you identify use after free in your program.