01 / 21

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.

\(\texttt{C++}\)

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

STACK (grows ↓) main() int x = 10; calculate() double result = 3.14; helper() char c = 'A'; Next frame goes here First In Last In First Out Last Out

The Heap: Flexible and Manual

HEAP (free store) int* arr new int[100] string* name new string() Node* head new Node() free free Widget* w new Widget() free free Blocks are scattered: not contiguous, not ordered

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:

✓ Fast
Stack allocation is essentially free: just a pointer move.
✓ Safe
Automatic deallocation on the stack prevents memory leaks.
✓ Flexible
Heap allocation lets you create data that outlives a function.

The Core Rules of Allocation

Stack Rules
• Size must be known at compile time
• Memory is freed automatically when scope ends
• Allocation/deallocation is extremely fast
• Limited size (typically 1-8 MB)
Heap Rules
• Size can be determined at runtime
• 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 grows ↓ Unused Space grows ↑ Heap Global/Static Data Code (Text) High addr Low addr auto variables new / delete

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

1
Is the size known at compile time? If yes, prefer the stack. Fixed-size arrays, simple variables, and structs work great.
2
Does the data need to outlive the current function? If yes, use the heap. Returning a pointer to a local stack variable is a bug.
3
Is the data very large? Arrays of millions of elements should go on the heap. The stack is typically limited to a few megabytes.
4
Do you need polymorphism? If you're storing objects through base-class pointers, heap allocation with \(\texttt{new}\) is the standard approach.
5
Always pair \(\texttt{new}\) with \(\texttt{delete}\). Better yet, use smart pointers (\(\texttt{unique\_ptr}\), \(\texttt{shared\_ptr}\)) to automate heap cleanup.

Example 1: Stack Allocation

void calculateArea() {
  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
Stack Frame: calculateArea() width 10 height 20 area 200 All freed when function returns

Example 2: Heap Allocation

void createArray() {
  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!
}
Stack n 1000 arr 0x7ff... Heap int[1000] [0, 2, 4, 6, ...] 4000 bytes Must call delete[] \(\texttt{arr}\) (on stack) points to data (on heap)

Example 3: The Memory Leak

void leakyFunction() {
  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
Stack data pointer DESTROYED ✕ Heap int[5000] still allocated No way to reach it! 20 KB wasted MEMORY LEAK Repeating this wastes more memory each time

The Smart Pointer Solution

// BAD: manual memory management
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.

Stack variable: scope = lifetime int x = 5; (visible and alive) { } freed Heap variable: scope ≠ lifetime ptr scope heap data lifetime (until delete) Leak if no delete called here! new delete

Common Mistakes to Avoid

✕ Dangling Pointer
Using a pointer after calling \(\texttt{delete}\). The memory may be overwritten by another allocation, causing unpredictable behavior.
✕ Forgetting delete
Every \(\texttt{new}\) must be matched with a \(\texttt{delete}\) (or \(\texttt{delete[]}\) for arrays). Forgetting causes a memory leak that grows over time.
✕ Returning Stack Address
Returning a pointer to a local variable. The stack frame is gone once the function returns, so the pointer is invalid.
✕ Double Delete
Calling \(\texttt{delete}\) on the same pointer twice. This corrupts the heap and can crash your program or create security holes.

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}\)?