/hiːp/

noun … “Dynamic memory area for runtime allocation.”

Heap is a region of memory used for dynamic allocation, where programs request and release blocks of memory at runtime rather than compile-time. Unlike the stack, which operates in a last-in, first-out manner, the heap allows arbitrary allocation sizes and lifetimes. Proper management of the heap is crucial to prevent fragmentation, leaks, and performance degradation.

Key characteristics of Heap include:

  • Dynamic allocation: memory can be requested and released at runtime using functions like malloc and free (C/C++), or via garbage collection in managed languages.
  • Non-linear access: blocks can be allocated and freed in any order.
  • Persistence: allocated memory remains valid until explicitly freed or reclaimed by a garbage collector.
  • Fragmentation: improper management can lead to gaps between allocated blocks, reducing usable memory.
  • Interaction with pointers: in low-level languages, heap memory is accessed via references or pointers.

Workflow example: Allocating and using heap memory in C++:

int* array = (int*) malloc(10 * sizeof(int))  -- Allocate 10 integers on the heap
for int i = 0..9:
    array[i] = i * 2
free(array)  -- Release memory back to the heap

Here, heap memory is dynamically allocated, used, and then explicitly freed to prevent leaks. In languages with automatic garbage collection, the runtime handles reclamation.

Conceptually, Heap is like a communal storage area where items can be placed and retrieved in any order, as opposed to a stack of plates where only the top plate is accessible at any time.

See Memory, Stack, Memory Management, Garbage Collection, Pointer.