💥 What is a Stack Overflow?
A stack overflow occurs when a program uses more stack memory than is available. Since the stack has a limited size (usually a few megabytes), exceeding that limit will crash the program — often with a segmentation fault or a runtime error like "stack overflow".
📉 How Can a Stack Overflow Happen?
Most commonly, stack overflows are caused by deep or infinite recursion or creating very large local variables on the stack.
🔁 1. Infinite or Deep Recursion
Each recursive call adds a new stack frame. If there's no proper base case or the depth is too large, the stack fills up quickly.
void recurse() {
recurse(); // no exit condition
}
➡ This function will call itself endlessly, pushing new stack frames until the stack overflows.
🧱 2. Large Local Variables
Declaring huge arrays or buffers inside a function can consume too much stack space.
void bigStackUsage() {
int arr[1000000]; // ~4MB of stack space if int = 4 bytes
}
➡ This might cause a stack overflow if the system's stack size is smaller than the required size.
🧰 How to Debug Stack Overflows
✅ 1. Identify Recursive Calls
Use a debugger like GDB or Visual Studio Debugger to:
- See the call stack (backtrace).
- Identify the function being called repeatedly.
(gdb) run
(gdb) backtrace
If you see the same function listed hundreds of times, it's likely infinite recursion.
✅ 2. Check for Large Stack Allocations
Look for very large arrays or buffers inside your functions. Consider moving them to:
- Heap memory using
malloc()
/free()
:
int* arr = malloc(1000000 * sizeof(int));
free(arr);
- Or make them global or static if appropriate.
✅ 3. Increase Stack Size (last resort)
If you have no recursion or big variables but still hit the limit:
- On Linux, increase stack size via shell:
ulimit -s unlimited
- On Windows, modify the stack size in the linker settings.
But this should only be done if you’ve ruled out design issues.
🧠 Summary
Cause | Description | Fix |
---|---|---|
Infinite Recursion | Function keeps calling itself with no stop | Add a proper base case |
Deep Recursion | Valid recursion but too deep | Convert to loop (if possible) or use heap |
Large Local Variables | Large arrays on stack | Allocate on heap or make static/global |
Small Stack Size | Stack limit is too low for legit use case | Increase stack size via system settings |
Would you like a hands-on example of a crashing recursive function and how to trace it in GDB?