Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

StackOverflowException and recursion limits

Reference for stack overflow in C#: why StackOverflowException cannot be caught, how deep recursion fails, and how to use explicit stacks or stack guards.

A stack overflow happens when the call stack runs out of space, almost always because of recursion that never ends or goes too deep. In .NET this is fatal: the runtime raises StackOverflowException, but you cannot catch it. The process is terminated immediately, finally blocks do not run, and no handler is called.

Each thread has a fixed stack (commonly 1 MB on Windows for secondary threads, 8 MB on Linux for the main thread). Each call uses part of it for arguments, locals and the return address. The only dependable defenses are to make sure recursion terminates, to limit its depth, or to replace it with a loop and an explicit stack.

C#
static int Forever(int n) => Forever(n + 1) + 1; // never returns: the process dies

Try it

C# Depth guard that fails safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Replacing recursion with an explicit stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public sealed class StackOverflowException : SystemException { }

// Guards in System.Runtime.CompilerServices
public static void RuntimeHelpers.EnsureSufficientExecutionStack();
public static bool RuntimeHelpers.TryEnsureSufficientExecutionStack();

public sealed class InsufficientExecutionStackException : SystemException { }
Member Description
EnsureSufficientExecutionStack() Throws InsufficientExecutionStackException if the remaining stack is too small for an average .NET method. Safe to catch.
TryEnsureSufficientExecutionStack() Returns false instead of throwing.
new Thread(start, maxStackSize) Starts a thread with a larger (or smaller) stack, in bytes.

Errors / undefined behavior: an actual StackOverflowException ends the process with no chance to recover. Output that had been buffered may be lost.

Usage notes

  • You cannot catch it. A try/catch around runaway recursion does nothing. Detect the problem before the stack is gone.
  • Always check the base case. Most overflows are a missing or unreachable terminating condition, for example a cyclic object graph in a recursive ToString.
  • Depth guards are cheap. RuntimeHelpers.EnsureSufficientExecutionStack() costs a few instructions and is what libraries such as serializers use for deeply nested input.
  • Untrusted input is a risk. Recursive parsers can be attacked with deeply nested data. Set a maximum depth (JsonSerializerOptions.MaxDepth defaults to 64).
  • Convert to iteration with a Stack<T> or Queue<T> when depth depends on data size, such as large graphs, linked lists or directory trees.
  • A bigger stack is a last resort. A Thread constructor with maxStackSize delays the failure rather than fixing it.
  • The compiler does not guarantee tail calls. C# does not eliminate tail recursion, so a tail-recursive method still grows the stack.
  • Async methods are different. An await that completes synchronously can nest calls; one that yields returns to the caller and does not add to the stack.