OS Stack Limits: How Deep Can Recursion Go?

Default stack sizes vary across operating systems, with typical limits like 1MB on Linux and 8MB on Windows, directly dictating the maximum safe recursion depth.

The top 3

  1. Default OS Stack Sizes: Windows vs. Linux vs. macOS: Operating systems allocate varying default stack sizes: Windows typically reserves 1 MB, while Linux often defaults to 8 MB for main threads, and macOS provides 8 MB for main threads but 512 KB for child threads.
  2. Top 3 Methods to Adjust OS Stack Limits: Developers can modify stack limits using OS-specific tools: `ulimit -s` on Unix-like systems (Linux, macOS) for current shell and child processes, linker options like `/STACK` (Windows) or `--stack` (GCC) during compilation, and `pthread_attr_setstacksize` for fine-grained control over individual thread stack sizes.
  3. Beyond Raw Size: 3 Key Factors Limiting Recursion Depth: The actual recursion depth is influenced by more than just raw stack size; key factors include the amount of local variables and parameters per function call (determining stack frame size), compiler optimizations like Tail-Call Optimization (TCO) which can reuse stack frames, and recursion inlining.

Sources

Open the full topic