Heap




Heap Structures


First we shall see what is chunk and it's structure .
Heap chunk exist's in 2 states

The following is Doug Lea’s idea of the heap structure using malloc and free :


In "In-use" state when we do malloc(15) the no of memory allocated is 15+4(for size chunk)+4(prev size of free chunk)+1(for alignment )
the size chunk is always multiple of 8 coz the last 3 bits are used as flags (refer above image)

Free'd state chunk has additional 8 bytes Forward ptr and a Backward ptr to next free chunk

There are two other really important fields: top and bins. The top field is a chunk of memory (the fundamental element of the allocator) and it’s where the data for which the space has been allocated are going to be stored. Each chunk in this is a memory fragment that can be allocated.

At the beginning, there’s only one big chunk in the arena (called wilderness), which is pointed by the top field itself: this chunk is always free and its size represents the free space of the arena.

Also it marks the end of the available space of the arena.
The bins array is composed by double-linked lists to chunks that were allocated and that were successively freed (this means that, at the beginning, all the bins are empty).

Each bin stores a list of chunks of specified size in order to allow the allocator to easily search for a free chunk, given the size
the research will be performed by starting looking for the smallest and best-fitting one.



So here comes the working of all .....

When a malloc is intially called it allocates memory from top chunk that is the top chunks gets split into 2 .
Now when free() is called it checks the size of chunk and if it is small it gets into fast-bin and if it is large it gets merged to top-chunk .

Now again if malloc is called it checks in the fast-bin if found that memory is used else it get's mem from top-chunk .