A “stack overflow” occurs when the program’s call stack runs out of memory. Recursive functions are a common culprit because every recursive call places a stack frame on that finite stack. If the depth of recursion is too large—either by design or by a logic error (infinite recursion)—the stack memory limit is exceeded and the runtime terminates with a StackOverflowError / Segmentation fault / RecursionError, depending on the language.
1. What Lives in a Stack Frame?
code
|---------------------------|
| Return address | ← tells CPU where to resume
| Saved registers |
| Parameters (arguments) |
| Local variables |
|---------------------------|
Each call—recursive or not—creates a new frame. When the function returns, that frame is popped off.
2. How Recursion Inflates the Stack
Consider a simple factorial routine:
c
long fact(long n) {
if (n == 0) return 1; // base case
return n * fact(n - 1); // recursive call
}
Calling fact(20) triggers 21 frames (n = 20 … 0).
Calling fact(20_000) triggers 20 001 frames—likely more than the OS-allocated stack (often ~1 MB per thread on Linux, 8 MB on macOS, ~1 MB on Windows).
If a base case is missing or unreachable, recursion runs indefinitely:
python
def forever():
return forever() # no base case ➜ infinite recursion
3. Language-Specific Reactions
Language
Typical Error
Default Stack Size (per thread, 64-bit)
C / C++
Segmentation fault
8 MB (Linux), 1 MB (Windows)
Java / Kotlin
StackOverflowError
~1 MB (configurable via -Xss)
Python
RecursionError: maximum recursion depth exceeded (soft limit ~1000, not the OS limit)
Same OS limits
Go
Grows stacks gradually, but still capped (default ≈ 1 GB per Goroutine, rarely hit)
—
4. Time vs. Space Complexity
Depth of recursion = d
• Time complexity: usually O(d) (same as iterative).
• Space complexity on call stack: O(d) — that’s the danger.
5. Mitigation Strategies
Iterative Rewrite
Replace recursion with an explicit loop or your own heap-allocated stack/queue.
python
# DFS iteratively
def dfs(root):
stack = [root] # uses heap, not call stack
while stack:
node = stack.pop()
...
Tail-Call Optimization (TCO)
Some compilers (Scheme, modern Swift under certain flags, GCC -O2 for simple tail calls) reuse the same frame when recursion is in tail position.
scheme
(define (fact-tail n acc)
(if (= n 0)
acc
(fact-tail (- n 1) (* acc n)))) ; tail call, optimized
Useful for algorithms that must be recursive but are provably bounded (e.g., quicksort on small arrays).
Check / Enforce Base Cases
Unit-test edge cases; add assertions:
cpp
long fact(long n) {
assert(n >= 0 && "n must be non-negative");
...
}
Hybrid Approaches
• Recursion + Memoization can reduce depth in some algorithms (e.g., Fibonacci via dynamic programming).
• Chunked Recursion: recurse until a safe depth, then switch to iteration.
6. Quick Visual
code
Depth 0 main()
Depth 1 quickSort()
Depth 2 quickSort() ← each call = 1 extra frame
Depth 3 quickSort()
...
Depth N ✖ StackOverflowError
7. Rule of Thumb
If worst-case recursion depth > ~10 000 (or unknown), assume stack overflow is probable unless:
• your language/runtime guarantees tail-call elimination, or
• you explicitly enlarged the stack.
Take-Away
Recursive algorithms are elegant and often match the problem’s structure, but the call stack is a finite resource. Always analyze maximum recursion depth and frame size—or refactor to iterative/heap-based solutions—to avoid the dreaded stack overflow.