Monday, 15 August 2016

c - How does "free" know how many bytes it has 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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...