What Is a Stack Overflow? When the Call Stack Runs Out
A stack overflow is the error you get when a program exceeds the fixed size of its call stack, almost always because too many nested function calls pile up.
The call stack has a hard size limit, and every function call uses a little of it. A stack overflow means that limit was crossed: the program tried to push one more frame than it had room for. The overwhelmingly common cause is recursion without a proper base case, so the function keeps calling itself forever.
Why the stack overflows
Each function call pushes a frame and only a return pops it. If calls keep nesting (especially uncontrolled recursion), frames accumulate until they exceed the stack limit. At that point the runtime raises a stack overflow and usually crashes the program.
Common causes
- Recursion with a missing or unreachable base case.
- Mutual recursion between functions that never terminates.
- Extremely deep but finite recursion on very large input.
- Accidental infinite loops of function calls via callbacks.
How to fix it
Make sure every recursive path has a base case that is actually reached. For very deep recursion, rewrite the algorithm iteratively or use an explicit data structure on the heap, which has far more room than the stack.
Stack overflow vs out of memory
A stack overflow exhausts the small, fixed call stack, usually from recursion. An out-of-memory error exhausts the much larger heap, usually from allocating too much data. They look similar (the program dies) but have different causes and fixes.
A quick example
A factorial function written as factorial(n) => n * factorial(n - 1) with no if (n <= 1) base case will recurse forever and overflow the stack instead of returning a result.
Stack overflows in CI
A stack overflow in a test is a deterministic bug: it fails the same way every time, so retrying is pointless. Latchkey treats deterministic crashes differently from transient infrastructure failures, auto-retrying only the latter so a genuine recursion bug is not masked.
Key takeaways
- A stack overflow means the call stack exceeded its fixed size, usually from runaway recursion.
- It differs from out-of-memory, which exhausts the heap rather than the stack.
- It is a deterministic bug, so retrying does not help; fix the recursion.