Runtime · intermediate
Stack overflow
A stack overflow occurs when execution requires more call-stack space than the runtime or operating environment permits. Deep or non-terminating recursion is a common cause, although unusually large stack allocations can also exhaust stack space in applicable languages.
Why it matters
A stack overflow is a resource and control-flow failure, not simply a slow algorithm. Recognizing it guides fixes such as correcting termination, reducing depth, using iteration, or moving large storage out of frames.
Mental model
How to reason about stack overflow
Each active nested call consumes some finite frame capacity. If calls keep accumulating faster than they return, the stack reaches a guard or limit and the runtime raises an error, terminates, or suffers language-specific unsafe behavior.
Analogy
A stack overflow is a pile of paused task cards reaching the ceiling because new subtasks keep arriving before earlier ones finish.
Examples
See the boundary, not just the happy path
Worked example · Unbounded self-call
def loop():
return loop()In standard Python implementations, each call adds recursive execution state until the interpreter's recursion guard raises RecursionError before uncontrolled native-stack exhaustion.
Worked example · Replace depth with explicit work
Use a loop and a stack collection to traverse a million-node chainPending nodes move into a separately managed collection rather than one runtime frame per node. Total memory can still be large, but it is not bounded by call-stack depth in the same way.
Useful contrast · Heap exhaustion is a different failure
Allocating objects until the allocator cannot satisfy another requestThat exhausts heap or process memory without requiring deep calls. Stack overflow and out-of-memory errors can have different limits, diagnostics, and remedies.
Common mistakes
Misconceptions to remove early
Increasing the stack before fixing missing progress
A larger limit only delays failure for recursion that never reaches a base case. Prove termination and bound maximum depth first.
Confusing stack overflow with stack buffer overflow
Stack exhaustion runs out of call-stack capacity. A stack-based buffer overflow writes outside an object's bounds and is a memory-safety vulnerability; the terms describe different mechanisms.
Quick check
Can you predict the result?
1. Which change fixes recursion that never progresses toward its base case?
- • Correct the recursive step so intended inputs reach a stopping case.
- • Increase the stack indefinitely.
- • Allocate a larger return value.
2. How does a stack buffer overflow differ from call-stack exhaustion?
Keep building