# C/C++: stack overflow — infinite recursion or huge local array (Segmentation fault, 0xC00000FD)

**Code:** `stack overflow` · **Category:** C/C++ · **Seen on:** C/C++, Linux, Windows

The call stack ran out of space, typically from recursion that never stops or from a very large array declared as a local variable.

## Meaning

Each function call uses stack memory (typically 8 MB on Linux, 1 MB on Windows). Unbounded recursion, deep but legitimate recursion on big inputs, and arrays like `int a[10'000'000];` inside a function exceed it. On Linux the process dies with a plain segmentation fault; on Windows you see `0xC00000FD`.

## Common causes

- Recursive function without a reachable base case
- Recursion depth proportional to input size (linked list, DFS on large graphs)
- Large arrays or objects declared as local variables
- Mutual recursion between functions or constructors/destructors
- Copy constructor that calls itself

## Quick fix

1. Fix or add the base case, and test depth with small inputs
2. Allocate big buffers with `std::vector` or `new` (heap) instead of on the stack
3. Convert deep recursion to a loop with an explicit stack

## Detailed fix by platform

### Linux

1. Check the limit: `ulimit -s` (kB); raise it for a test with `ulimit -s unlimited`
2. In gdb, `bt 20` shows the same frames repeating

### Visual Studio

1. Project properties → Linker → System → Stack Reserve Size, or `/STACK:8388608`; the real fix is to remove the recursion

## Code examples

### Heap instead of stack

```cpp
#include <vector>

long long sum_to(long long n) {              // infinite if called with n < 0
    if (n <= 0) return 0;                    // base case
    return n + sum_to(n - 1);
}

int main() {
    // int big[5'000'000];                   // 20 MB on the stack: crashes
    std::vector<int> big(5'000'000);         // heap: fine
    return static_cast<int>(sum_to(1000) % 256);
}
```

## How to diagnose

1. **Backtrace** — Does the same function repeat?
2. **Size** — Any large local arrays?
3. **Input** — How deep does the recursion get?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/stack-overflow-infinite-recursion)
