A stack overflow error occurs when a program's call stack exceeds its maximum allocated size, almost always because a recursive function calls itself too many times without ever reaching a base case. In Python, the interpreter raises a RecursionError: maximum recursion depth exceeded, stopping the program before it crashes the operating system.

What is the call stack?

Every time a function is called, Python creates a stack frame — a block of memory holding the function's local variables, the arguments passed to it, and the return address (where execution should resume after the function finishes). These frames are stacked on top of each other in the call stack.

When the function returns, its frame is popped off the stack and execution resumes in the frame below. The stack grows with each call and shrinks with each return. Under normal use, the stack grows a little and then shrinks again. Under recursion, the stack grows one frame deeper with every recursive call — and if no call ever returns, the stack eventually runs out of space.

Stack depth What is on the stack
Frame 1 main() calls factorial(5)
Frame 2 factorial(5) calls factorial(4)
Frame 3 factorial(4) calls factorial(3)
… …
Frame 1000 Python raises RecursionError

Python's default recursion limit is 1,000 calls. This is a safety guard — hitting the limit almost always means there is a bug (a missing base case), not that you genuinely needed more depth.

How does an infinite recursion cause a stack overflow?

A correctly written recursive function has two parts: a base case that stops the recursion, and a recursive case that calls itself with a simpler version of the problem. Missing or incorrect base cases cause infinite recursion.

Correct recursion (with base case):

def factorial(n):
    if n == 0:           # base case: stop here
        return 1
    return n * factorial(n - 1)   # recursive case

print(factorial(5))   # 120

The call chain is: factorial(5) → factorial(4) → factorial(3) → factorial(2) → factorial(1) → factorial(0) → returns 1. The stack grows 6 frames deep and then unwinds completely.

Broken recursion (missing base case):

def factorial(n):
    return n * factorial(n - 1)   # no base case!

print(factorial(5))
# RecursionError: maximum recursion depth exceeded

Without the if n == 0: check, the function calls factorial(-1), then factorial(-2), forever. Python raises RecursionError after 1,000 frames.

What does the error message look like?

When Python's recursion limit is exceeded, you see:

Traceback (most recent call last):
  File "example.py", line 2, in factorial
    return n * factorial(n - 1)
  File "example.py", line 2, in factorial
    return n * factorial(n - 1)
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded in comparison

The repeated line — shown hundreds of times — is the diagnostic fingerprint of infinite recursion. Whenever you see a line repeated many hundreds of times in a traceback, look immediately for a missing or unreachable base case.

How do you fix a stack overflow / RecursionError?

The three common fixes are:

  1. Add or correct the base case — the most common fix. Check that the base case is reachable given the initial argument and that each recursive call moves towards it.

  2. Convert to an iterative solution — any recursive function can be rewritten as a loop. Loops do not consume call-stack space, so there is no depth limit:

def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
  1. Increase the recursion limit — Python allows this via sys.setrecursionlimit(n), but it is almost always the wrong solution. It delays the crash and masks the underlying bug. Only use it when you are certain the recursion is correct and legitimately deep (e.g., traversing a very large tree).

How do stack overflow errors relate to security?

Stack overflow vulnerabilities in low-level languages (C, C++) are a significant security concern. In those languages, a stack overflow can overwrite adjacent memory, potentially allowing an attacker to inject and execute malicious code — a technique called stack buffer overflow exploitation. Python's managed memory and explicit RecursionError prevent this class of attack entirely. At GCSE, this distinction illustrates one reason why higher-level languages with automatic memory management are safer for general-purpose programming.

Frequently asked questions

Why does Python limit recursion to 1,000 calls?

The limit exists to prevent Python from crashing the operating system or consuming unlimited memory — both of which could happen if unbounded recursion were allowed. Most legitimate recursive algorithms on typical GCSE datasets need far fewer than 1,000 frames. If you hit the limit, the almost-certain cause is a missing base case, not insufficient depth.

Is a stack overflow the same as a memory leak?

No. A stack overflow exhausts the call stack — a fixed region of memory used for function frames — and happens almost instantly when recursion goes wrong. A memory leak occurs when a program allocates heap memory (for objects and data) and fails to release it, causing memory usage to grow slowly over time. Both are memory-related bugs, but they arise from different mechanisms and are diagnosed differently.

Can non-recursive code cause a stack overflow?

Yes, in principle. If a chain of function calls (A calls B, B calls C, C calls D, …) goes thousands of levels deep without any of those functions returning, the stack will eventually overflow even without explicit recursion. This is rare in practice for non-recursive code, but it can occur in deeply nested event handlers or certain object serialisation routines. The fix is the same: break the deep call chain or convert to an iterative approach.

How does the call stack relate to the stack data structure?

The call stack uses the same Last In First Out (LIFO) principle as a stack data structure. The most recently called function is at the top; when it returns, it is popped off and the previous frame is at the top again. Understanding the stack data structure (push, pop, peek) directly helps you understand how function calls work at a lower level — one of the reasons stacks appear in both the data structures and the computer systems sections of GCSE syllabuses.


Trace through recursive functions and debug stack errors with Professor Turing at aitutors.me.