01 / 21

Avoiding
Stack Overflow

Learn why unbounded recursion crashes your C++ programs and how to limit recursion depth to keep your stack safe.

C++

What Is the Call Stack?

Every time your program calls a function, the system pushes a stack frame onto the call stack. Each frame stores local variables, the function's parameters, and a return address so the program knows where to continue after the function finishes.

main() computeSum() helper() Growth Bottom Top

What Is Recursion?

A recursive function is one that calls itself to solve a smaller instance of the same problem. Each call adds a new frame to the stack.

int factorial(int n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // recursive call }

What Is Stack Overflow?

A stack overflow occurs when the call stack exceeds its memory limit. The most common cause is unbounded recursion: a recursive function that never reaches its base case, or one that recurs too deeply.

Stack Limit f(n) f(n-1) f(n-2) f(n-3) f(n-4) f(n-5) ✕ OVERFLOW Segfault!

The Core Rule

A typical stack can hold roughly 10,000 to 100,000 frames (depending on frame size and stack limit). If your recursion might exceed that, you must refactor or guard it.

Safe Recursion
depth \( < \) stack limit
base case always reached Unsafe Recursion depth unbounded or no base case

Recursion Depth Visualized

The recursion depth is the maximum number of stack frames that exist simultaneously. For a simple linear recursion, depth equals the input size \( n \).

Input size n Stack frames Limit 100 10k 50k 100k Safe Overflow

Recursion vs Iteration

Recursion Iteration
Stack usage \( O(n) \) frames \( O(1) \) frames
Overflow risk High for large \( n \) None
Code clarity Often cleaner Can be verbose
Speed Function call overhead Faster in practice
When to use Trees, divide-and-conquer Simple loops, large \( n \)

How to Apply the Rule

1
Identify your base case. Make sure every recursive path eventually hits a condition that stops further calls.
2
Estimate maximum depth. For input size \( n \), how deep will the recursion go? If \( \text{depth} \approx n \) and \( n \) can be large, you have a problem.
3
Add a depth parameter. Pass a counter that increments each call. If it exceeds a safe limit, stop and return an error or fallback.
4
Consider converting to iteration. Any recursion can be rewritten with an explicit stack or a loop, using only \( O(1) \) call-stack frames.

Example 1: Dangerous Recursion

This function has no base case guard: if someone passes a negative number, it recurs forever.

int countDown(int n) { // BUG: what if n is negative? if (n == 0) return 0; return 1 + countDown(n - 1); }

Example 1: Fixed Version

int countDown(int n) { if (n <= 0) return 0; // safe base case return 1 + countDown(n - 1); }

However, for very large \( n \) (e.g., \( n = 10^6 \)), this still overflows the stack because \( \text{depth} = n \). We need more protection.

Example 2: Depth-Limited Recursion

const int MAX_DEPTH = 10000; int solve(int n, int depth = 0) { if (n <= 0) return 0; if (depth >= MAX_DEPTH) { // Fallback: switch to iteration return n; // or throw, or use a loop } return 1 + solve(n - 1, depth + 1); }

Example 3: Iterative Conversion

The safest strategy: replace recursion with a loop. This uses only one stack frame regardless of input size.

Recursive
int sum(int n) {
  if (n <= 0) return 0;
  return n + sum(n-1);
}
Iterative
int sum(int n) {
  int total = 0;
  for (int i=1; i<=n; i++)
    total += i;
  return total;
}

Example 4: Tree Recursion

Binary tree traversal is naturally recursive. The depth equals the height of the tree, which is \( O(\log n) \) for balanced trees but \( O(n) \) for skewed ones.

Balanced: depth = 3 1 2 3
Skewed: depth = \(n\)
1 2 3 4 ...

Three Strategies to Stay Safe

1. Depth Guard
Pass a depth counter and bail out when it hits a safe limit.
2. Convert to Loop
Rewrite the recursion as an iterative loop with an explicit stack data structure.
3. Tail Recursion
Write the recursive call as the last operation. Some compilers optimize this to a loop (but C++ does not guarantee it).

Common Mistakes

✕ Missing Base Case
Forgetting the termination condition entirely: the function recurs infinitely.
✕ Wrong Comparison
Using \(== 0\) instead of \(\le 0\), so negative inputs bypass the base case.
✕ Trusting Tail Call Optimization
Assuming the compiler will optimize tail recursion. C++ does not guarantee this.

Summary Table

Scenario Max Depth Safe? Fix
factorial(20) 20 Yes None needed
factorial(\(10^6\)) \(10^6\) No Use a loop
Balanced BST (10k nodes) \(\approx 14\) Yes None needed
Skewed BST (10k nodes) 10,000 Risky Depth guard
No base case \(\infty\) No Add base case

Question 1 of 5

What is the primary cause of stack overflow in a C++ program?

Question 2 of 5

What is the recursion depth of calling factorial(n) with the standard recursive implementation?

Question 3 of 5

Which of the following is the most reliable way to prevent stack overflow in C++?

Question 4 of 5

A recursive function uses if (n == 0) as its base case. What happens when you call it with \( n = -5 \)?

Question 5 of 5

Traversing a balanced binary search tree of \( n \) nodes uses a recursion depth of approximately: