Stack vs Heap Memory: Differences Explained
A running program uses two main regions of memory for its data. The stack holds function call frames: local variables, arguments and return addresses. It is managed automatically and is very fast, but small and tied to the lifetime of each function call. The heap holds memory that the program requests explicitly, such as with malloc or new, and it lives until it is freed. The heap is flexible and large but slower, and it is where leaks and fragmentation happen.
| Aspect | Stack | Heap |
|---|---|---|
| Used for | Function call frames: local variables, arguments, return addresses | Dynamically allocated data that must outlive a function or whose size is not known in advance |
| Allocation | Automatic: the stack pointer moves on each call and return | Explicit: malloc and free, new and delete, or a garbage collector |
| Speed | Very fast: just adjusting a pointer | Slower: the allocator must find a free block and keep records |
| Lifetime | Until the function returns | Until the memory is freed (or garbage collected) |
| Size | Limited (typically a few megabytes per thread) | Limited only by the available memory |
| Layout | Usually grows downward from high addresses | Usually grows upward from lower addresses, so the two grow toward each other |
| Fragmentation | None | Possible: repeated allocation and freeing can leave unusable gaps |
| Threads | Each thread has its own private stack | Shared by all threads, so the allocator must be thread-safe |
| Typical errors | Stack overflow from deep recursion or large local arrays | Memory leaks, use after free, double free and running out of memory |
Figures are typical orders of magnitude and vary by process generation and product.