cd /blog
Feb 21, 2025

Memory Regions - Heap

#memory | #lowlevel | #cache

The heap is used for dynamic memory allocation. This is where memory is allocated during runtime using languages' allocation mechanisms (e.g., new in Java, malloc(), calloc(), realloc() in C). Unlike the stack—which automatically manages plates, you must manually request and release memory space. If you don't avoid extra excessive allocations or if you forget to clean up, you'll ended up understanding what they mean by memory leak.

Key Characteristics

  • Manual allocation and deallocation if a garbage collector is not available;
  • Larger and more flexible than the stack, but slower to access;
  • Memory is allocated dynamically and can grow as needed (within system limits);
  • Objects or data allocated on the heap stay there until they are explicitly freed;
  • When a program exits, the operating system automatically reclaims all allocated heap memory;

Limitations

  • The objects in the heap are not automatically freed if a garbage collector is not available;
  • Risk of memory leak exception if used size excceds available memory;
  • Possibly the slowest memory region to work with, not counting virtual memory;
  • High pressure on a garbage collector (when available) may also be a problem;

Example

#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)); // Allocate memory for an int if (ptr == NULL) { printf("Memory allocation failed!\n"); return 1; } *ptr = 42; // Assign a value printf("Heap value: %d\n", *ptr); free(ptr); // Free memory return 0; }
We use cookies to make interactions with our websites and services easy and meaningful. By using this website you agree to our use of cookies. Learn more.