What is Heap Allocation?

Heap allocation is the most flexible allocation scheme. Allocation and deallocation of memory can be done at any time and any place depending upon the user's requirement. Heap allocation is used to allocate memory to the variables dynamically and when the variables are no more used then claim it back.

Heap management is specialized in data structure theory. There is generally some time and space overhead associated with heap manager. For efficiency reasons, it may be useful to handle small activation records of a particular size as a special case, as follows −

  • For each size of interest, keep the linked list of free blocks of that size.
  • If possible fill the request for size s with a block of size S’, where S’ is the smallest size greater than or equal to s. When the block is deallocated return back to the linked list.
  • For a larger block of storage use the heap manager.

There are two methods used for Heap management are as follows −

Garbage Collection Method

When the all-access path to an object is destroyed, but data object continues to exist, such types of objects are said to be garbage. Garbage collection is a technique that is used to reuse that object space.

In garbage collection, firstly, we mark all the active objects, and all the remaining elements whose garbage collection is 'on' are garbaged and returned to the free space list.

Reference Counter

By reference counter, an attempt is made to reclaim each element of heap storage immediately after it can no longer be accessed.

Each memory cell on the heap has a reference counter associated with it that contains a count of the number of values that points to it. The count has incremented each time a new value point to the cell and decremented each time an amount ceases to point to it. When the counter becomes zero, the cell is returned to the free list for further allocation.

Properties of Heap Allocation

There are various properties of heap allocation which are as follows −

  • Space Efficiency− A memory manager should minimize the total heap space needed by a program.
  • Program Efficiency− A memory manager should make good use of the memory subsystem to allow programs to run faster. As the time taken to execute an instruction can vary widely depending on where objects are placed in memory.
  • Low Overhead− Memory allocation and deallocation are frequent operations in many programs. These operations must be as efficient as possible. That is, it is required to minimize the overhead. The fraction of execution time spent performing allocation and deallocation.