Programming Search⌘K

Conceptcore

Stack overflow

Also called stack overflow error, StackOverflowError, RecursionError, maximum call stack size exceeded, too much recursion, maximum recursion depth.

A stack overflow happens when the calls that have not returned need more space than the call stack has. Deep or endless recursion is the usual cause.

Applies to
core-languages

Idea

The call stack has a fixed size. Each call that has not returned holds a stack frame on it, so a chain of calls that is too deep fills it. A stack overflow "occurs if the call stack pointer exceeds the stack bound"1. In some languages the program gets an error that it can catch. In others, the program crashes.

import sys


def depth(n):
    if n == 0:
        return 0
    return 1 + depth(n - 1)          # one frame for each step


def loop(n):
    count = 0
    while n > 0:                     # one frame for the whole loop
        n -= 1
        count += 1
    return count


print("depth(100) =", depth(100))
try:
    depth(1_000_000)
except RecursionError:
    print("depth(1000000): RecursionError, the limit is", sys.getrecursionlimit())
print("loop(1000000) =", loop(1_000_000))
Output
depth(100) = 100
depth(1000000): RecursionError, the limit is 1000
loop(1000000) = 1000000

depth(100) needs 100 frames and works. depth(1000000) would need a million frames, and Python stops it with an error. The loop computes the same count in one frame.

How it works

The cause. "The most common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack"1. A function with no base case never stops. MDN describes the JavaScript error as one that "occurs when there are too many function calls, or a function is missing a base case"2. A function with a base case can still overflow if the input is large, as depth(1000000) does above.

Large locals. "The other major cause of a stack overflow results from an attempt to allocate more memory on the stack than will fit, for example by creating local array variables that are too large"1. A C function with a local array of 1048576 doubles "consumes 8 megabytes of data"1, which can be more than the whole stack.

Threads. Each thread has its own stack, and the size can differ. "most programs with threads have less stack space per thread than a program with no threading support"1. A program that works on its main thread can overflow on another thread.

What happens. In C and C++, the program tries "to access memory beyond the call stack's bounds", and this is "typically resulting in a program crash"1. For a C function that calls itself with no end, Wikipedia says the stack overflows, "resulting in a segmentation fault"1. A virtual machine or an interpreter checks the depth and reports an error:

  • The JVM: "If the computation in a thread requires a larger Java Virtual Machine stack than is permitted, the Java Virtual Machine throws a StackOverflowError"3.
  • Python: RecursionError "is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit() ) is exceeded"4.
  • JavaScript: the engines throw RangeError: Maximum call stack size exceeded in Chrome and Safari, and InternalError: too much recursion in Firefox2.
  • .NET: "You can't catch a StackOverflowException object with a try /catch block, and the corresponding process is terminated by default"5.
  • Go: a goroutine stack grows as needed, up to a limit. "If any goroutine exceeds this limit while growing its stack, the program crashes"6.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin on the JVM gets the same StackOverflowError as Java, and the program can catch it. No example file exists because kotlinc is not installed.
SQLDoes not applyA plain query has no recursion of functions.
BashNative
PowerShellNativeFunctions can call themselves, and each call uses stack space. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no calls.
CSSDoes not applyCSS has no calls.
Regular expressionsDoes not applyA regular expression has no calls.
Language Verdict What happens and how to change the limit
Python native RecursionError, which the program can catch; sys.setrecursionlimit sets the limit
JavaScript native RangeError or InternalError, which the program can catch
TypeScript native as in JavaScript
Java native StackOverflowError, which the program can catch; a Thread constructor takes a stack size
Kotlin native as in Java
C# native StackOverflowException, which ends the process; a Thread constructor takes a stack size
Go native the goroutine stack grows; past the limit of debug.SetMaxStack, the program crashes
Rust native the program aborts; thread::Builder::stack_size sets the size for a thread
C native a crash, often a segmentation fault; ulimit -s sets the limit of the shell
C++ native as in C
Bash native the FUNCNEST variable sets a limit on the nesting of functions
PowerShell native functions can call themselves, and each call uses stack space
SQL n/a a plain query has no recursion of functions
Regex n/a a pattern has no calls
HTML n/a HTML has no calls
CSS n/a CSS has no calls

The example files run the same three steps. Python, JavaScript, TypeScript and Java catch the error. C#, C and C++ cannot catch it, so they count the depth and stop at a limit before the stack runs out. Go grows the stack and finishes. Rust runs the deep call on a thread with a large stack. Bash sets FUNCNEST.

PythonGitHub
import sys


def depth(n):
    if n == 0:
        return 0
    return 1 + depth(n - 1)          # one frame for each step


def loop(n):
    count = 0
    while n > 0:                     # one frame for the whole loop
        n -= 1
        count += 1
    return count


print("depth(100) =", depth(100))
try:
    depth(1_000_000)
except RecursionError:
    print("depth(1000000): RecursionError, the limit is", sys.getrecursionlimit())
print("loop(1000000) =", loop(1_000_000))
Output
depth(100) = 100
depth(1000000): RecursionError, the limit is 1000
loop(1000000) = 1000000
  • Verdict: native. Python counts the frames of Python functions and raises RecursionError past the limit. The program can catch it, and sys.setrecursionlimit changes the limit.
#include <iostream>
#include <optional>

constexpr int limit = 10000; // well below the depth where the stack runs out

// Returns no value when the depth passes limit, so the stack never overflows.
std::optional<long> depth(long n, int level = 1) {
    if (level > limit) return std::nullopt;
    if (n == 0) return 0;
    auto rest = depth(n - 1, level + 1);
    if (!rest) return std::nullopt;
    return 1 + *rest;
}

long loop(long n) {
    long count = 0;
    while (n > 0) { // one frame for the whole loop
        n--;
        count++;
    }
    return count;
}

int main() {
    std::cout << "depth(100) = " << *depth(100) << "\n";
    if (!depth(1000000)) {
        std::cout << "depth(1000000): stopped at the limit of " << limit << "\n";
    }
    std::cout << "loop(1000000) = " << loop(1000000) << "\n";
}
Output
depth(100) = 100
depth(1000000): stopped at the limit of 10000
loop(1000000) = 1000000
  • Verdict: native. As in C, nothing checks the depth, and an overflow usually crashes the process.
JavaGitHub
public class Main {
    static int depth(int n) {
        return n == 0 ? 0 : 1 + depth(n - 1); // one frame for each step
    }

    static int loop(int n) {
        int count = 0;
        while (n > 0) { // one frame for the whole loop
            n--;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println("depth(100) = " + depth(100));
        try {
            depth(1_000_000);
        } catch (StackOverflowError e) {
            System.out.println("depth(1000000): StackOverflowError");
        }
        System.out.println("loop(1000000) = " + loop(1_000_000));
    }
}
Output
depth(100) = 100
depth(1000000): StackOverflowError
loop(1000000) = 1000000
  • Verdict: native. The JVM throws StackOverflowError when a thread needs more stack than it may have. It is an Error, not an Exception, so catch (Exception e) does not catch it.
  • A Thread constructor takes a stack size, but its effect depends on the platform.
#include <stdio.h>

#define LIMIT 10000 /* well below the depth where the stack runs out */

/* Returns -1 when the depth passes LIMIT, so the stack never overflows. */
static long depth(long n, int level) {
    if (level > LIMIT) return -1;
    if (n == 0) return 0;
    long rest = depth(n - 1, level + 1);
    return rest < 0 ? rest : 1 + rest;
}

static long loop(long n) {
    long count = 0;
    while (n > 0) { /* one frame for the whole loop */
        n--;
        count++;
    }
    return count;
}

int main(void) {
    printf("depth(100) = %ld\n", depth(100, 1));
    if (depth(1000000, 1) < 0) {
        printf("depth(1000000): stopped at the limit of %d\n", LIMIT);
    }
    printf("loop(1000000) = %ld\n", loop(1000000));
    return 0;
}
Output
depth(100) = 100
depth(1000000): stopped at the limit of 10000
loop(1000000) = 1000000
  • Verdict: native. C does not check the depth. A call past the end of the stack usually ends in a segmentation fault, and the program cannot recover. The program counts its own depth and stops first.
  • ulimit -s in Bash sets the maximum stack size for the programs that the shell starts.
using System;

static class Demo
{
    const int Limit = 10_000; // well below the depth where the stack runs out

    // Returns -1 when the depth passes Limit, so the stack never overflows.
    static int Depth(int n, int level)
    {
        if (level > Limit) return -1;
        if (n == 0) return 0;
        int rest = Depth(n - 1, level + 1);
        return rest < 0 ? rest : 1 + rest;
    }

    static int Loop(int n)
    {
        int count = 0;
        while (n > 0) // one frame for the whole loop
        {
            n--;
            count++;
        }
        return count;
    }

    static void Main()
    {
        Console.WriteLine($"depth(100) = {Depth(100, 1)}");
        if (Depth(1_000_000, 1) < 0)
        {
            Console.WriteLine($"depth(1000000): stopped at the limit of {Limit}");
        }
        Console.WriteLine($"loop(1000000) = {Loop(1_000_000)}");
    }
}
Output
depth(100) = 100
depth(1000000): stopped at the limit of 10000
loop(1000000) = 1000000
  • Verdict: native. A stack overflow throws StackOverflowException, but a try/catch cannot catch it, and the process ends. The program counts its own depth and stops first, as the .NET documentation advises.
JavaScriptGitHub
function depth(n) {
  return n === 0 ? 0 : 1 + depth(n - 1); // one frame for each step
}

function loop(n) {
  let count = 0;
  while (n > 0) { // one frame for the whole loop
    n--;
    count++;
  }
  return count;
}

console.log("depth(100) =", depth(100));
try {
  depth(1_000_000);
} catch (e) {
  console.log("depth(1000000):", e.constructor.name);
}
console.log("loop(1000000) =", loop(1_000_000));
Output
depth(100) = 100
depth(1000000): RangeError
loop(1000000) = 1000000
  • Verdict: native. The engine has a fixed stack and throws an error when it runs out. Here it is RangeError, as in Chrome and Safari. Firefox throws InternalError instead.
  • The program can catch the error and go on.
TypeScriptGitHub
function depth(n: number): number {
  return n === 0 ? 0 : 1 + depth(n - 1); // one frame for each step
}

function loop(n: number): number {
  let count = 0;
  while (n > 0) { // one frame for the whole loop
    n--;
    count++;
  }
  return count;
}

console.log("depth(100) =", depth(100));
try {
  depth(1_000_000);
} catch (e) {
  console.log("depth(1000000):", e instanceof RangeError ? "RangeError" : "another error");
}
console.log("loop(1000000) =", loop(1_000_000));
Output
depth(100) = 100
depth(1000000): RangeError
loop(1000000) = 1000000
  • Verdict: native. The program runs as JavaScript, so the error is the one that the engine throws. In a catch, the type of e is unknown, so the code tests it with instanceof.
package main

import "fmt"

func depth(n int) int {
	if n == 0 {
		return 0
	}
	return 1 + depth(n-1) // one frame for each step
}

func loop(n int) int {
	count := 0
	for n > 0 { // one frame for the whole loop
		n--
		count++
	}
	return count
}

func main() {
	fmt.Println("depth(100) =", depth(100))
	fmt.Println("depth(1000000) =", depth(1_000_000))
	fmt.Println("loop(1000000) =", loop(1_000_000))
}
Output
depth(100) = 100
depth(1000000) = 1000000
loop(1000000) = 1000000
  • Verdict: native. A goroutine stack starts small and grows as the calls need it, so a million frames fit. Past the limit that debug.SetMaxStack sets, the program crashes.
RustGitHub
use std::thread;

fn depth(n: u64) -> u64 {
    if n == 0 { 0 } else { 1 + depth(n - 1) } // one frame for each step
}

fn looped(mut n: u64) -> u64 {
    let mut count = 0;
    while n > 0 { // one frame for the whole loop
        n -= 1;
        count += 1;
    }
    count
}

fn main() {
    println!("depth(100) = {}", depth(100));
    let big = thread::Builder::new()
        .stack_size(256 * 1024 * 1024) // 256 MiB for this thread
        .spawn(|| depth(1_000_000))
        .unwrap();
    println!("depth(1000000) on a 256 MiB stack = {}", big.join().unwrap());
    println!("loop(1000000) = {}", looped(1_000_000));
}
Output
depth(100) = 100
depth(1000000) on a 256 MiB stack = 1000000
loop(1000000) = 1000000
  • Verdict: native. Rust does not set the stack size of the main thread, and the platform decides it. A thread made with thread::Builder::stack_size gets the size that it asks for, so the deep call runs there.
BashGitHub
# depth sets result to n, with one function call for each step.
depth() {
  local n=$1
  if (( n == 0 )); then
    result=0
    return
  fi
  depth $((n - 1))
  result=$((result + 1))
}

loop() {
  local n=$1 count=0
  while (( n > 0 )); do # one call for the whole loop
    n=$((n - 1))
    count=$((count + 1))
  done
  result=$count
}

depth 100
echo "depth(100) = $result"
if ( FUNCNEST=1000; depth 100000 ) 2>/dev/null; then
  echo "depth(100000) finished"
else
  echo "depth(100000): stopped by FUNCNEST=1000"
fi
loop 100000
echo "loop(100000) = $result"
Output
depth(100) = 100
depth(100000): stopped by FUNCNEST=1000
loop(100000) = 100000
  • Verdict: native. With FUNCNEST set, a call past the nesting level aborts the command, and here the subshell ends with a failure. Without it, very deep recursion can crash Bash.
  • The example uses 100000, not 1000000, because a loop in Bash is slow.
  • The limit is a setting. Python sets a depth, not a size: sys.setrecursionlimit will "Set the maximum depth of the Python interpreter stack to limit"7. "This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python"7. In Java, a thread can ask for a stack size, but "The effect of the stackSize parameter, if any, is highly platform dependent"8. In Rust, "The default stack size is platform-dependent and subject to change", and "the stack size of the main thread is not determined by Rust"9. In Bash, the ulimit option -s sets "The maximum stack size"10, and FUNCNEST "defines a maximum function nesting level"11.
  • Tail calls. "some compilers implement tail-call optimization", so that endless tail recursion can run "without stack overflow"1. Scheme and some other languages "require all implementations to include tail-recursion as part of the language standard"1. In a language without that rule, a tail call may still use a frame. See recursion.
  • An accumulator. A function that passes its partial result to the next call, such as pow_accum(base, exp - 1, accum * base), is a tail call, so a tail-call optimizer can "drop" the prior stack frames1.

Pitfalls

  • A higher limit can crash. To raise the Python limit "should be done with care, because a too-high limit can lead to a crash"7. The limit counts frames, and the real C stack may run out first.
  • Recursion on input data. A function that recurses once for each item of a list, or once for each level of a tree, overflows on large input. Test with large input, or use a loop.
  • Catching the error. In .NET the error cannot be caught, so "you should write your code to detect and prevent a stack overflow"5. In Java, StackOverflowError is an Error, not an Exception12.
  • A setter that calls itself. In JavaScript, a setter that assigns to its own property calls itself again: MDN shows that this.name = name inside set name is infinitely recursive2.

Cost

A recursion that is too deep "can be fixed by transforming the recursion into a loop and storing the function arguments in an explicit stack (rather than the implicit use of the call stack)"1. The explicit stack is on the heap, which is much larger than the call stack. To raise the stack size instead costs address space for each thread: "specifying a lower value may allow a greater number of threads to exist concurrently"8.

History

The languages added their own ways to report and limit the error. StackOverflowError was in Java from version 1.012. Go added debug.SetMaxStack in Go 1.2, and its initial setting "is 1 GB on 64-bit systems, 250 MB on 32-bit systems"6. Python added RecursionError in version 3.5. Before it, "a plain RuntimeError was raised"4.

References

  1. Stack overflow, Wikipedia, Introduction; Causes; Constrained environment
  2. InternalError, too much recursion, MDN Web Docs, Message; What went wrong?; Examples
  3. The Structure of the Java Virtual Machine, Java Virtual Machine Specification, Java SE 21, 2.5.2 Java Virtual Machine Stacks
  4. Built-in Exceptions, Python 3.14 documentation, RecursionError
  5. StackOverflowException Class, .NET API documentation, Remarks
  6. runtime/debug, Go standard library, func SetMaxStack
  7. sys, Python 3.14 documentation, sys.getrecursionlimit; sys.setrecursionlimit
  8. Thread, Java SE 21 API, Thread(ThreadGroup, Runnable, String, long)
  9. Module std::thread, Rust standard library, Stack size
  10. Bash Builtin Commands, Bash Reference Manual, ulimit
  11. Bash Variables, Bash Reference Manual, FUNCNEST
  12. StackOverflowError, Java SE 21 API, Class StackOverflowError

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/1J4BHR/text.yaml