Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does free() defragment?

Tags:

c

Assuming two blocks allocated by malloc() that are internally next each other(who knows they next each other? just assumption), after free() two blocks, are they emerged into one unallocated block? Not sure, please help. Thanks.


2 Answers

This fully depends on the implementation. Some allocators do consolidate, some do if certain conditions are met, some don't. It's not something you can assume in any way though. If this is an issue, find a solution that does not depend on such assumption (e.g manage a fixed pool yourself).

like image 76
nielsj Avatar answered Jul 02 '26 12:07

nielsj


That depends entirely on the implementation of the allocator. There are many different implmentations, some of which perform coalescing of adjacent free memory.

Edit: Here's a research paper that describes various allocation techniques and benchmarks their effect on fragmentation. I think their conclusion is that address-ordered free block lists (which make for easy coalescing) perform very well.

like image 21
Michael Borgwardt Avatar answered Jul 02 '26 13:07

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!