Stack vs. Heap
Memory Allocation
Understand how C++ manages memory in two fundamentally different regions: the stack for fast, automatic storage and the heap for flexible, dynamic allocation.
What is Memory Allocation?
Every variable, object, and array in your \(\texttt{C++}\) program needs a place to live in your computer's RAM. Memory allocation is the process of reserving that space so your program can store and retrieve data.
\(\texttt{C++}\) gives you two main regions to allocate memory: the Stack and the Heap. Understanding when and how to use each is a core skill.
The Stack: Fast and Automatic
The Heap: Flexible and Manual
Why Does This Matter?
Choosing the wrong allocation strategy leads to real problems: crashes, memory leaks, slow performance, and security vulnerabilities. Understanding stack vs. heap helps you write code that is:
The Core Rules of Allocation
• Memory is freed automatically when scope ends
• Allocation/deallocation is extremely fast
• Limited size (typically 1-8 MB)
• You must free memory manually with \(\texttt{delete}\)
• Allocation/deallocation is slower
• Much larger (limited by system RAM)
Memory Layout of a C++ Program
Stack vs. Heap: Side by Side
| Stack | Heap | |
|---|---|---|
| Speed | Very fast | Slower |
| Managed by | Compiler (automatic) | Programmer (manual) |
| Lifetime | Until scope ends | Until you call \(\texttt{delete}\) |
| Size limit | Small (1-8 MB) | Large (GBs of RAM) |
| Size known at | Compile time | Runtime |
| Fragmentation | None | Possible |
| Risk | Stack overflow | Memory leaks |
How to Decide Which to Use
Example 1: Stack Allocation
int width = 10; // stack
int height = 20; // stack
int area = width * height; // stack
std::cout << area; // prints 200
} // width, height, area are ALL freed here
Example 2: Heap Allocation
int n = 1000; // stack
int* arr = new int[n]; // heap!
for(int i = 0; i < n; i++)
arr[i] = i * 2;
delete[] arr; // YOU must free it!
}
Example 3: The Memory Leak
int* data = new int[5000];
// ... use data ...
return; // Oops! Forgot delete[]!
} // "data" pointer is destroyed (stack)
// but the 5000 ints on the heap are STILL THERE
// and now UNREACHABLE = memory leak
The Smart Pointer Solution
int* raw = new int(42);
// ... if an exception happens here, leak!
delete raw;
// GOOD: automatic cleanup
#include <memory>
std::unique_ptr<int> smart =
std::make_unique<int>(42);
// Automatically deleted when smart goes out of scope
// Even if an exception is thrown!
Scope vs. Lifetime
Scope is where a variable name is visible in code. Lifetime is how long the memory actually exists. On the stack, these are the same. On the heap, they can be very different.
Common Mistakes to Avoid
Summary: When to Use Each
| Scenario | Use Stack | Use Heap |
|---|---|---|
| Simple local variables | ✓ | |
| Small fixed arrays | ✓ | |
| Size unknown at compile time | ✓ | |
| Data outlives function scope | ✓ | |
| Very large data structures | ✓ | |
| Polymorphic objects | ✓ | |
| Short-lived temporary values | ✓ |
Question 1 of 5
Which of the following variables is allocated on the \(\texttt{heap}\)?
Question 2 of 5
What happens to stack-allocated variables when a function returns?
Question 3 of 5
A function allocates memory with \(\texttt{new}\) but never calls \(\texttt{delete}\). What problem does this cause?
Question 4 of 5
You need to create an array whose size is determined by user input at runtime. Which approach is correct?
Question 5 of 5
What is the primary advantage of using \(\texttt{std::unique\_ptr}\) instead of raw \(\texttt{new}\)/\(\texttt{delete}\)?