Identifying a Stack Overflow
What you'll learn: You will learn how infinite recursion exhausts the memory set aside for function calls, causing your program to crash.
The Leaning Tower of Functions
Every time your program calls a function, it places a "frame" on the Call Stack. Think of this like a physical stack of trays in a cafeteria. Each tray represents a function's local variables and its place in line. When a function finishes, the tray is removed.
However, the stack has a fixed height. If you keep adding trays without ever taking them off, you will eventually hit the ceiling. In programming, this "hitting the ceiling" is called a Stack Overflow.
How It Happens: The Infinite Loop
The most common cause of a stack overflow is a recursive function (a function that calls itself) that never reaches an ending point. Because the first function call can’t finish until the second one does, and the second can’t finish until the third does, the stack grows taller and taller until the computer runs out of allocated memory for that stack.
#include <stdio.h>
void push_too_far(int count) {
printf("Level: %d\n", count);
// This function calls itself forever.
// Each call adds a new frame to the stack.
push_too_far(count + 1);
}
int main() {
push_too_far(1);
return 0;
}
Spotting the Crash
When you run code like the example above, it won't just run forever like an infinite while loop might. Instead, the program will suddenly stop.
On many systems, you will see a message like Segmentation fault (core dumped) or Stack overflow. The program terminates because it tried to use memory that didn't belong to it—the space "above the ceiling." If you are using a debugger, you’ll notice the "call stack" window filled with thousands of entries of the exact same function.
To fix this, you must ensure every recursive function has a base case: a conditional statement that allows the function to return without making another call, finally allowing the stack of trays to be cleared.
Key takeaway
A stack overflow occurs when too many active function calls pile up, exhausting the program's reserved memory and causing an immediate crash.