Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "free" know how many bytes it has to free [duplicate]

Tags:

c

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?

like image 501
Luke Avatar asked Oct 15 '11 17:10

Luke


2 Answers

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.

like image 125
Mysticial Avatar answered Oct 23 '22 22:10

Mysticial


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.

like image 27
pndc Avatar answered Oct 23 '22 23:10

pndc