Avoiding
Stack Overflow
Learn why unbounded recursion crashes your C++ programs and how to limit recursion depth to keep your stack safe.
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.
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.
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.
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.
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 \).
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
Example 1: Dangerous Recursion
This function has no base case guard: if someone passes a negative number, it recurs forever.
Example 1: Fixed Version
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
Example 3: Iterative Conversion
The safest strategy: replace recursion with a loop. This uses only one stack frame regardless of input size.
if (n <= 0) return 0;
return n + sum(n-1);
}
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.
Three Strategies to Stay Safe
Common Mistakes
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: