What is the Heap
The heap is a region of memory used for dynamic allocation. Unlike the stack, where memory is automatically managed by function calls and returns, the heap lets you allocate bytes explicitly and keep them alive for as long as you need.
How it works
When your program needs memory whose size isn't known at compile time — a user's input string, a growing list, a downloaded file — it asks the heap allocator for a block. In C, this is malloc. In Rust, it's Box::new or Vec. The allocator finds a free region large enough, marks it as used, and returns a pointer.
When you're done, you free the memory (free in C, automatic drop in Rust). The allocator marks that region as available for future requests.
This flexibility comes with costs:
- Speed — heap allocation requires searching for a free block and updating bookkeeping. It's slower than the stack, where allocation is just a pointer bump.
- Fragmentation — after many allocations and frees, the heap can become a patchwork of used and free blocks. A request for 1 KB might fail even if 10 KB total is free, because no single contiguous block is large enough.
- Bugs — in languages without garbage collection, forgetting to free causes memory leaks. Freeing too early causes use-after-free. Freeing twice causes corruption. These are among the most common sources of security vulnerabilities.
Modern allocators (jemalloc, mimalloc, the system allocator) use arenas, size classes, and thread-local caches to reduce fragmentation and contention. Languages like Rust prevent use-after-free at compile time through ownership rules.
Why it matters
Most data in a real program lives on the heap. Every string, collection, and network buffer that outlives a single function call is heap-allocated. Understanding the heap explains why some allocations are expensive, why memory leaks happen, and why languages invest so heavily in managing heap lifetimes — whether through garbage collection, reference counting, or ownership.
See How Memory Works for how stack and heap fit into a process's virtual memory layout.