Separate areas with different rules
The heap and the stack are different regions of memory, and a C++ program uses each in its own way. Both live in RAM, but they follow different rules. The stack holds automatic variables, which are created and destroyed with their scope. The heap holds memory you request with new or malloc and free yourself.
Comparison
| Aspect | Stack | Heap |
|---|---|---|
| Who manages it | The compiler and runtime, based on scope | You, with new and delete or malloc and free |
| When memory is released | When the scope ends | When you release it |
| Order | Last in, first out | No fixed order |
| Typical speed | Usually faster | Usually slower |
| Typical size | Smaller | Larger |
| Common errors | Stack overflow, pointers to local variables | Leaks, double deletes, dangling pointers |
Both in one example
#include <iostream>
int main()
{
int onStack = 10; // automatic storage, usually on the stack
int* onHeap = new int(20); // dynamic storage, on the heap
std::cout << onStack << " " << *onHeap << "\n"; // prints 10 20
delete onHeap; // you release the heap memory
return 0; // onStack is released here automatically
}
Two things are in this program. onStack is an ordinary local variable. onHeap is also a local variable, so the pointer itself lives in the stack frame, but the integer it points to lives on the heap. Only delete releases that integer. Forgetting the delete would leak it, even though the pointer goes away when main returns.
The C++ standard describes storage durations
The standard speaks of storage durations rather than stack and heap. Local variables have automatic storage duration. Objects created with new have dynamic storage duration. How those objects are laid out in memory is up to the compiler and runtime. A compiler may keep a local variable in a register, and it can reuse memory in ways that don’t show in the source code.
Which one to reach for
- Use stack variables by default. They are simpler, and they are cleaned up for you.
- Use the heap when the size or lifetime is only known at runtime.
- Prefer containers such as
std::vectorand smart pointers such asstd::unique_ptrover rawnewanddelete.
For the full comparison, read about c heap vs stack.