The short answer
Heap memory is used when a program needs data the stack can’t handle well. That usually means data whose size is only known at run time, data that must stay alive after the function that created it returns, or data that several parts of a program need to share.
When the size isn’t known in advance
A function’s stack frame is generally sized ahead of time, and the stack as a whole is limited. That makes the stack a poor place for data whose size depends on user input, a file or a network response.
Suppose a program reads lines from a file of unknown length and stores them. The number of lines isn’t known until the file has been read, so the storage has to grow as the program goes. Storage like this is usually allocated on the heap, where the program can request space as it needs it. The mechanics of that request are covered in what is memory allocation.
When the data has to outlive the function
Consider a function that builds an array of results and returns it to its caller. If the array lived in the function’s stack frame, it would be gone as soon as the function returned. Here is a C version that uses the heap:
#include <stdlib.h>
int *make_squares(int n) {
int *squares = malloc(n * sizeof *squares); // lives on the heap until freed
for (int i = 0; i < n; i++) {
squares[i] = i * i;
}
return squares; // still valid after the function returns
}
The caller is responsible for calling free on the returned pointer once it’s done with the array. If the array were declared as a plain local variable instead, returning a pointer to it would be a bug.
When several parts of a program share data
Heap objects can be reached through references from many places: several functions, several objects or several threads. Stack data belongs to one call on one thread, and it disappears when that call ends. Data that more than one part of the program needs to use after a call ends is a good reason to put it on the heap.
When the structure grows and changes shape
Linked lists, trees and graphs are built from nodes created while the program runs, and each node refers to others. Those nodes are usually allocated on the heap, so they can be added and removed as the program works. A stack frame can’t simply grow to hold a structure like that.
The trade-offs
Heap memory has costs. Allocation is usually slower than pushing a stack frame. The program has to release heap memory, either by hand or through a garbage collector. Over time, the heap can become fragmented, with many small free gaps that are hard to reuse. Data that is never released causes memory leaks.
For a full comparison of the two regions, see the difference between stack and heap memory.
When the stack is the better choice
Small values that are used briefly and have a known size, such as loop counters and temporary values, usually belong on the stack. Stack allocation needs no separate search for space, and the memory comes back automatically when the function returns.
Readers often search for is heap the same as stack. The answer is no. The two regions serve different jobs, and most programs use both.
Key takeaways
- Use heap memory for data whose size is unknown in advance, data that must outlive a function call, and data that is shared across the program.
- Stack memory suits short-lived values with a known size.
- The heap offers flexibility, and in exchange it takes more management and is usually slower to allocate.