Sub topic 13
Stack Depth Limits and Stack Overflow
This chapter assumes you know how the call stack stores one frame per active call, and that you have compared recursive and iterative versions of the same function. It explains what happens when a chain of recursive calls grows too deep.
Why Depth Has a Cost
Every recursive call pushes a new stack frame. That frame holds the call's arguments, its local variables, and the place to return to. The frame stays on the stack until the call returns. A function like total(items) on a list of length n keeps n + 1 frames alive at its deepest point. That means its stack space is O(n), even though a loop computing the same sum uses O(1).
Stack memory is limited. If frames keep piling up, the program eventually runs out. In languages such as C this is a stack overflow, and the process usually crashes. CPython protects itself by counting active Python frames and stopping at a fixed limit.
Seeing the Limit in Python
import sys
print(sys.getrecursionlimit()) # often 1000 by default in CPython
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
try:
depth(100000)
except RecursionError as e:
print("RecursionError:", e)The function is correct, because it has a base case and every call makes progress toward it. It fails only because reaching that base case takes 100,000 nested calls, far more than the limit allows. A missing base case gives the same error, but much faster. If you see RecursionError, check whether the recursion never stops or just runs too deep.
Common Mistakes
- Raising the limit as a fix.
sys.setrecursionlimit(10**6)removes Python's safety check but does not give the process more stack memory. A deep enough chain can then crash the interpreter with a segmentation fault instead of raising a catchable exception. - Assuming small test inputs prove safety. A recursive list or linked-list function passes on 10 items and fails on 10,000 in production.
- Ignoring the depth of the input's shape. A balanced tree with a million nodes has a depth of about 20. A degenerate tree where every node has only one child has a depth of a million.
Your Options
| Situation | Approach |
|---|---|
| Depth is O(log n) | Keep the recursion |
| Linear depth, simple accumulation | Rewrite as a loop |
| Deep trees or graphs | Use an explicit stack (covered later) |
| Language with guaranteed tail calls | Tail-recursive form (covered later) |
Exercise
The function total(items) returns items[0] + total(items[1:]) and returns 0 for an empty list. What happens when you call it on list(range(5000)) in default CPython, and what is the simplest fix?
Show answer
It raises RecursionError. The chain needs about 5001 nested frames, which exceeds the default limit of about 1000. The simplest fix is to use a loop or the built-in sum(items), which uses constant stack space. Raising the recursion limit is not a reliable fix.
Exercise
A recursive function on a binary search tree works on random data but fails on input inserted in sorted order. Why?
Show answer
Inserting items in sorted order produces a degenerate tree shaped like a linked list. Its depth equals the number of nodes, so the recursion depth grows linearly and exceeds the limit.