Possible Duplicate:
C programming : How does free know how much to free?
In C the function malloc takes an argument, specifiying how many bytes to alloacte. How ever the function free doesn't take any arguments but a pointer. How does free know how many bytes it has to free?
This information such as the size of the allocation is kept within the memory allocator itself.
Internally, there's some data-structure that keeps a list of all the active memory allocations, their sizes, and their addresses. Exactly how it works is fairly complicated as there are lot of different memory allocation algorithms suited for different purposes and allocation sizes.
Often times, the size is stored as a fixed offset just below the address returned by malloc()
, but that's just an implementation detail.
A fairly common way is for the allocation to increase the allocation by sizeof(size_t) and store the length at the start, before returning a pointer to the rest of the memory allocated. Freeing the memory then just involves looking at the length that was stashed away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With