Sub topic 13
Stack Depth Limits and Stack Overflow
This chapter assumes you know how the call stack holds one frame per active call, and that you can read the factorial, list-sum, tree-height, and merge sort functions from earlier chapters. We look at what happens when recursion goes too deep, how CPython reports it, and how to estimate whether a recursive function is safe for the inputs it will get.
Why the Stack Has a Limit
Each recursive call pushes a stack frame. A frame holds the function's local variables, its arguments, and the place to resume when the call returns. Frames are freed only when their call returns, so a chain of n nested calls keeps n frames alive at the same time.
Stack memory is finite. The operating system gives each thread a fixed stack region, often 8 MB on Linux for the main thread and less for other threads. A program that uses up that region has a stack overflow. In C or C++ this usually crashes the process with a segmentation fault and no useful message.
CPython adds its own guard in front of the hardware limit. It counts how deep the Python calls are nested. When the count passes a configured recursion limit, it raises RecursionError, an ordinary exception you can catch, instead of crashing.
Seeing the Limit in CPython
import sys
print(sys.getrecursionlimit()) # often 1000 by default in CPython
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
print(depth(500)) # 500, well under the limit
try:
depth(100000)
except RecursionError as e:
print("RecursionError:", e)The message reads maximum recursion depth exceeded, sometimes followed by a short context phrase. The function is correct. It has a base case and every call moves toward it. It fails only because the input needs more frames than the limit allows.
You can measure the usable depth directly:
def probe(n=1):
try:
return probe(n + 1)
except RecursionError:
return n
print(probe()) # slightly below sys.getrecursionlimit()The result comes out a little below the limit because frames already on the stack count too: the module-level code, print, and anything else that called you. Your function does not start at depth zero. A function that works in a quick script can fail when it is called from deep inside a framework, a test runner, or another recursive function.
Two Different Failures with the Same Error
RecursionError shows up in two situations, and you fix them differently.
| Cause | Example | Fix |
|---|---|---|
| Infinite recursion: the base case is missing or never reached | `factorial(-1)` with base case `n == 0` | Fix the logic: validate input, use `n <= 0`, or make sure each call actually shrinks the input |
| Finite recursion that is too deep | `depth(100000)`, sum of a 50,000-item list | Reduce depth, or rewrite with a loop or an explicit stack |
Look at the traceback to tell them apart. Infinite recursion shows the same line repeated with arguments that never approach the base case. Deep recursion shows arguments steadily moving toward the base case but too far away from it. Raising the limit cannot fix infinite recursion. It only makes the crash take longer.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
try:
factorial(-1) # -1, -2, -3, ... never hits 0
except RecursionError:
print("no progress toward the base case")Estimating Stack Depth Before It Fails
The stack space a recursive function uses equals its maximum depth times the size of one frame. The total number of calls does not matter. What matters is the longest chain of calls active at the same moment. That chain is the longest path from the root of the call tree to a leaf.
| Function | Total calls | Maximum depth |
|---|---|---|
| `factorial(n)` | n + 1 | n + 1 |
| `total(items)` on a list of length n | n + 1 | n + 1 |
| Naive `fib(n)` | about 1.6ⁿ | n |
| `merge_sort` on n items | about 2n | about log₂ n + 1 |
| `height(node)` on a balanced tree of n nodes | about 2n | about log₂ n + 1 |
| `height(node)` on a degenerate tree of n nodes | about 2n | n + 1 |
This table gives a practical decision rule. Recursion that peels off one element per call, like factorial and total, has depth proportional to the input size. Python can only safely handle inputs in the hundreds that way. Recursion that halves the input, like merge sort, has logarithmic depth. A million items needs only about 21 levels, so depth is never the problem there. Naive fib is exponentially slow, yet its depth is only n. Its cost is time, not stack.
The Degenerate Tree Trap
Tree recursion is only shallow when the tree is balanced. A binary search tree built from already-sorted keys turns into a linked list, with every node having only a right child. Its height equals its node count.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
# Build a chain of 5000 nodes, each only a right child (built with a loop).
root = None
for v in range(5000):
root = Node(v, right=root)
try:
print(height(root))
except RecursionError:
print("tree too deep for recursive height()")The same height function that handles a balanced tree of a million nodes fails on this 5000-node chain. When the input comes from users, files, or parsed data such as deeply nested JSON, you cannot assume the shape is balanced.
Raising the Limit, and Why It Is Risky
sys.setrecursionlimit(n) changes CPython's counter. It does not make the real stack any bigger.
import sys
sys.setrecursionlimit(20000)
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
print(depth(15000)) # 15000Raising the limit modestly, for example to a few thousand when you know the input is bounded, is a reasonable choice. Raising it far beyond what the real stack can hold swaps a catchable RecursionError for a hard crash of the interpreter. How many frames fit depends on the Python version, the platform, and whether the recursion passes through C code such as json, pickle, repr, or comparison methods. CPython 3.12 and later track Python-level and C-level recursion separately, but the general rule still applies.
A common workaround runs the recursion in a thread with a larger stack:
import sys
import threading
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
def main():
sys.setrecursionlimit(200000)
print(depth(100000)) # 100000
threading.stack_size(256 * 1024 * 1024) # 256 MB, set before creating the thread
t = threading.Thread(target=main)
t.start()
t.join()This shows up in competitive programming, but it is fragile in production code. The maximum stack size depends on the platform, the memory is reserved per thread, and the depth is still bounded.
Decision Criteria
Ask these questions about any recursive function:
- Is the maximum depth bounded by a small constant or by log n? If so, recursion is safe. Merge sort and balanced-tree operations fall here.
- Does depth grow linearly with input size? If inputs can reach the high hundreds, assume it will fail in CPython. Use a loop for linear processing of lists and numbers.
- Does the data's shape control the depth (trees, nested structures)? If the data is untrusted or might be degenerate, plan for depth equal to its size.
- Is the language one that guarantees tail-call optimization? Some languages, such as Scheme, can run certain recursive forms in constant stack. CPython does not. A later chapter covers tail recursion.
When the answer points away from plain recursion, you have two standard rewrites. A loop works for linear recursion. An explicit stack works for tree-shaped recursion. Both are covered in the following chapters.
Exercise
A function walks a nested Python list such as [1, [2, [3, [4]]]] and recurses once for each level of nesting. It works in your tests but raises RecursionError on a production file. Is this infinite recursion or excessive depth, and what would you check in the traceback to confirm?
Show answer
Most likely excessive depth: the production data is nested more deeply than the test data, and depth equals the nesting level. In the traceback, check whether each successive frame receives a more deeply nested sublist that is getting closer to a non-list element (excessive depth) or the same argument over and over (infinite recursion). The fix is an explicit-stack traversal, because the nesting depth depends on input you do not control.
Exercise
Give the maximum stack depth, in terms of n, for (a) total(items) on a list of n items, (b) merge_sort on n items, and (c) naive fib(n). Which of these can fail with RecursionError for n = 5000 under the default limit of 1000?
Show answer
(a) about n + 1, (b) about log2(n) + 1, which is about 13 for n = 5000, (c) about n. Both total and naive fib exceed the limit at n = 5000, although naive fib would take impossibly long well before depth became a problem. merge_sort is safe.