Sub topic 5
Depth Limits and Stack Overflow
This chapter assumes you know what a stack frame is and how the call stack grows and shrinks during recursion, as covered in the earlier chapters. You should also be able to read Python functions and simple Big-O expressions. The chapter explains why a recursive call can fail even when the logic is correct, how Python and other languages report that failure, and how to predict which inputs will trigger it.
Why recursion has a depth limit
Every active call keeps a frame on the call stack. The frame holds the call's parameters, local variables, and return address. A loop reuses one frame no matter how many times it repeats. A recursive function adds one frame per nested call, and those frames stay on the stack until the base case returns.
The stack is a fixed region of memory. A typical thread gets somewhere between 1 MB and 8 MB, depending on the operating system and how the thread was created. When nested calls use up that space, the program has a stack overflow: there is no room for the next frame.
Languages respond to this in two ways:
- They check depth in software and raise a catchable error before memory runs out. CPython does this.
- They let the hardware or operating system detect the overflow, which usually crashes the process. C and C++ do this.
How CPython reports it: RecursionError
CPython keeps a counter of nested Python calls and compares it to a limit. The limit is usually 1000.
import sys
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
print(sys.getrecursionlimit()) # typically 1000 in CPython
try:
depth(100_000)
except RecursionError as e:
print("RecursionError:", e)The message reads maximum recursion depth exceeded. The limit is a safety margin, set well below what the real stack could hold. CPython uses it so that a runaway recursion becomes an ordinary exception and does not crash the interpreter.
The usable depth is a little less than the limit, because frames already on the stack also count. That includes the module's own frame and any caller frames. You can measure it:
import sys
def probe(n=0):
try:
return probe(n + 1)
except RecursionError:
return n
print("limit:", sys.getrecursionlimit())
print("reached depth:", probe()) # a number slightly below the limitThe exact number depends on the Python version and how you run the script. A REPL, an IDE, or a test runner each put a different number of frames under your code.
Depth is not the same as the number of calls
A common mistake is to assume that a function making many calls must be in danger of overflowing. Overflow depends on the maximum depth, meaning the longest chain of calls active at the same time. The total number of calls does not matter.
calls = 0
max_depth = 0
def fib(n, d=1):
global calls, max_depth
calls += 1
max_depth = max(max_depth, d)
if n < 2:
return n
return fib(n - 1, d + 1) + fib(n - 2, d + 1)
fib(25)
print(calls, max_depth) # 242785 25Naive Fibonacci makes almost a quarter of a million calls here, yet the stack never holds more than 25 frames. Its problem is time. A linear recursion over a 5,000-element list makes only 5,000 calls, but it fails, because all 5,000 frames are live at the same moment.
Predicting depth from the shape of the recursion
To judge whether an input is safe, express the maximum depth as a function of input size.
| Recursion shape | Example | Maximum depth |
|---|---|---|
| Shrink by one each call | `factorial(n)`, recursive list sum | O(n) |
| Halve the problem each call | binary search, balanced merge sort | O(log n) |
| Follow a balanced tree | traversal of a balanced BST | O(log n) |
| Follow an unbalanced tree | BST built from sorted input, linked list | O(n) |
| Two branches, each shrinking by one | naive Fibonacci | O(n) |
| Missing or unreachable base case | `factorial(-1)` | unbounded |
The same algorithm can land in different rows depending on the data. A recursive tree traversal is safe on a balanced tree of a million nodes, because the depth is about 20. On a degenerate tree where every node has only a right child, the same code needs a million frames.
Splitting the work so that depth grows logarithmically is often enough to avoid the limit:
def sum_linear(xs, i=0):
if i == len(xs):
return 0
return xs[i] + sum_linear(xs, i + 1)
def sum_halving(xs, lo=0, hi=None):
if hi is None:
hi = len(xs)
if hi - lo == 0:
return 0
if hi - lo == 1:
return xs[lo]
mid = (lo + hi) // 2
return sum_halving(xs, lo, mid) + sum_halving(xs, mid, hi)
data = list(range(10_000))
print(sum_halving(data)) # 49995000
try:
sum_linear(data)
except RecursionError:
print("linear version too deep")Both functions make about the same number of calls. sum_halving needs only about 14 levels of depth, while sum_linear needs 10,001.
Infinite recursion: the other cause
Some overflows come from a bug and not from large input. If the base case can never be reached, the depth grows until the limit stops it.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
try:
factorial(-1) # -1, -2, -3, ... never reaches 0
except RecursionError:
print("base case unreachable")
def factorial_safe(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial_safe(n - 1)Make the base case cover every value where the recursion should stop, for example n <= 0 and not only n == 0, or validate the input at the entry point. A RecursionError on small input almost always points to this bug.
Raising the limit, and what it costs
You can raise CPython's limit with sys.setrecursionlimit. This only moves the software check. It does not make the real stack bigger. Set the limit high enough, and the native stack can run out first, which crashes the interpreter with a segmentation fault and no Python traceback.
If you need deep recursion, run it in a thread whose stack you size yourself:
import sys
import threading
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
def main():
print(depth(50_000)) # 50000
sys.setrecursionlimit(60_000)
threading.stack_size(64 * 1024 * 1024) # 64 MB for threads created after this
t = threading.Thread(target=main)
t.start()
t.join()Catching RecursionError is not a fix
Catching the exception works for probing and for reporting a clear error. It is a poor control-flow tool for three reasons:
- When the error is raised, the work done in the frames being unwound is lost, and any shared state those frames changed may be left half-updated.
- The depth at which the error happens depends on the caller's stack, so the same call can succeed in one context and fail in another.
- Code that runs in the
exceptblock near the limit has very little stack left, so calling more functions there can raise again.
How other languages behave
| Language or runtime | What happens on overflow | Controlling the size |
|---|---|---|
| CPython | `RecursionError` at the software limit; segfault if the native stack runs out first | `sys.setrecursionlimit`, `threading.stack_size` |
| Java | `StackOverflowError` (an `Error`, not an `Exception`) | `-Xss` JVM flag, or a `Thread` constructor stack size |
| JavaScript (V8) | `RangeError: Maximum call stack size exceeded` | engine flags only; not portable |
| C / C++ | usually a segmentation fault; formally undefined behavior | linker or `ulimit -s` settings, thread attributes |
| Go | goroutine stacks grow on demand; fatal error at a max (1 GB by default on 64-bit) | `debug.SetMaxStack` |
Languages that guarantee tail-call optimization, such as Scheme, can run certain recursive functions in constant stack space. CPython does not do this, so tail recursion in Python still uses one frame per call. A later chapter covers tail calls in detail.
Checklist for spotting overflow risk
- Write the maximum depth as a function of input size.
- Find the largest input the code will realistically see, including worst-case shapes such as sorted data or degenerate trees.
- Compare that depth with the limit, about 1000 in CPython, or the default stack size in other languages.
- If depth grows linearly with input that can be large or untrusted, restructure the code to reduce depth or convert it to iteration.
Exercise
A recursive function counts the nodes in a binary search tree. It works on a tree of 1,000,000 random keys but raises RecursionError on a tree built by inserting the keys 1 to 5,000 in increasing order. Explain why.
Show answer
The depth of the recursion equals the height of the tree. Random insertions give a height of roughly 2 to 3 times log2(n), about 40 to 60 for a million keys, which is far below the limit. Inserting sorted keys makes every node a right child of the previous one, so the tree becomes a chain with height 5,000. That needs about 5,000 frames, which is more than CPython's default limit of 1000.
Exercise
Naive fib(30) makes over 2.6 million calls. Will it raise RecursionError under the default limit of 1000? What is its real problem?
Show answer
No. Its maximum depth is about 30, because each chain of calls lowers n by at least 1 until it reaches the base case. Its real problem is exponential running time, since the same subproblems are recomputed many times. Memoization or a bottom-up loop fixes that.
Exercise
A colleague "fixes" a RecursionError by calling sys.setrecursionlimit(10**7) and processing a list with 2 million elements through linear recursion. The program now exits with a segmentation fault. What happened, and what is a better fix?
Show answer
The higher limit turned off CPython's software check, but the native thread stack, usually a few megabytes, could not hold 2 million frames. The process ran out of real stack memory and crashed. A better fix is to rewrite the function as a loop, use an explicit stack, or restructure it so the depth grows logarithmically. Running it in a thread with a much larger stack would also work, but it is fragile.