Sub topic 5
Depth Limits and Stack Overflow
This chapter assumes you know what a stack frame is and how each recursive call pushes a new frame onto the call stack, as covered in the earlier chapters. It shows what happens when that stack gets too deep.
Why the Stack Has a Ceiling
Every call that has not yet returned keeps its frame on the call stack. A recursive function that calls itself n times before reaching its base case needs about n frames alive at the same moment. The amount of memory per frame is fixed, but the stack does not grow forever. Operating systems give each thread a fixed stack region, often around 8 MB for the main thread on Linux and less for other threads. Language runtimes may add their own cap on top of that.
When the number of frames goes past the cap, the program fails. This failure is called a stack overflow. A loop does not have this problem, because it reuses one frame no matter how many times it runs.
Python's Recursion Limit
CPython counts nested Python calls and raises RecursionError once the count passes a limit, which is 1000 by default. This is a deliberate guard, so you get a catchable exception instead of a crash.
import sys
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
def depth_loop(n):
count = 0
while n != 0:
count += 1
n -= 1
return count
print(sys.getrecursionlimit()) # typically 1000 in CPython
try:
depth(100_000)
except RecursionError as e:
print("RecursionError:", e)
print(depth_loop(100_000)) # 100000, no errorBoth functions compute the same result. The recursive one needs 100,001 frames at once. The loop needs one.
How Other Languages Fail
| Language | What happens on overflow |
|---|---|
| Python (CPython) | `RecursionError` at the interpreter's limit |
| Java | `StackOverflowError` when the thread stack is exhausted |
| JavaScript (V8) | `RangeError: Maximum call stack size exceeded` |
| C / C++ | Usually a segmentation fault. The behavior is undefined and cannot be caught portably. |
Common Mistakes
- Missing or unreachable base case. If
nnever reaches the base case (for example,depth(-1)above), the recursion never stops, and every input overflows. If you see aRecursionErroron a small input, check the base case before blaming the limit. - Raising the limit as the fix.
sys.setrecursionlimit(10**6)removes Python's guard but does not enlarge the real stack. Deep enough recursion can then crash the interpreter outright, especially when the calls go through C code. Treat raising the limit as a stopgap for known, bounded depths. - Testing only small inputs. A recursive function over a linked list or a degenerate tree works fine in tests with 50 nodes. In production it can fail on 50,000. Depth grows with input size, so check how deep the recursion gets on realistic inputs.
Later chapters show two ways to remove the depth problem: turning tail recursion into a loop, and managing your own stack on the heap.
Exercise
A recursive function sums a Python list by returning lst[0] + recsum(lst[1:]), with an empty list as its base case. Will recsum(list(range(5000))) succeed under CPython's default settings? What depth does it need, and what change avoids the problem without touching the recursion limit?
Show answer
It fails with RecursionError. It needs about 5001 nested frames (one per element plus the empty-list call), and the default limit is about 1000. Rewriting it as a loop that adds each element to a running total uses a single frame and works for any list length. Calling the built-in sum() also works. As a side benefit, the loop avoids the O(n^2) copying caused by the lst[1:] slices.
Exercise
Why does depth(-1) raise RecursionError even though -1 is a small number?
Show answer
The base case checks n == 0, and n - 1 moves away from 0 when n is negative. The base case is never reached, so the recursion continues until it hits the limit.