Heap management

Heap is a linear block of memory which is used to handle pointer allocation and deallocation. Heap performs two operations, allocate and free. Allocate operation takes input as size in bytes and returns pointer to block of memory of defined size. If no memory exists, it returns null pointer. Free operation is used to free the allocated block. Pascal uses new and dispose, where as C+ uses new and delete for allocate and free operation respectively. C language uses malloc and free as a part of standard library
stdlib.h for allocation and dellocating memory. The prototype of these functions are as follows

void *malloc (unsigned size);
void free (void *ptr);

One way of implementing heap is maintaining a circular list of free blocks, from which memory can be drawn through malloc function and returned through free function. Though this is very simple to implement and maintain, it has few disadvantages. One of the disadvantage is that, the pointer to free block may not be the one given to malloc. Possibility of user giving invalid pointer corrupts the heap. Secondly there can be small fragments of free blocks. This has to be compacted so that large blocks of continuous memory are available for malloc.

More efficient way of heap implementation is using circular linked list which keeps track of both allocated and free blocks. Heap consists of nodes (blocks) which has information of size of used area and size of free area followed by user space and free space as shown below.



 It also has next pointer which points to next block in heap memory. Heap also uses one more pointer called memptr this points to a block that has some free space. This free space will always be initialized to null value.


0 comments