Infinite recursion hazards
What you'll learn: How to prevent your programs from crashing due to a "Stack Overflow" by understanding the physical limits of recursive functions.
The bottomless pit of memory
Imagine you are building a tower of blocks. Each time your function calls itself, you place a new block on top. In C, these blocks are called "stack frames." They hold the function's variables and the address of where to return when finished.
The problem? Your computer does not have an infinite supply of blocks. The "Stack" is a specific, limited slice of memory allocated to your program. If a recursive function calls itself too many times without stopping, you run out of space. The tower topples, and your program crashes instantly with a "Stack Overflow" error.
The missing "Exit" sign
The primary cause of infinite recursion is a missing or broken base case. The base case is the condition that tells the function, "Stop here; don't call yourself again." Without it, the function is like a pilot who forgets how to land—they will fly until they run out of fuel.
Even if you have a base case, you can still crash if your logic never actually reaches it. This is common if your "step" toward the base case is moving in the wrong direction.
#include <stdio.h>
// HAZARDOUS: This function has no way to stop!
void countdown(int n) {
printf("%d... ", n);
// Danger: We forgot the 'if (n <= 0) return;' base case.
// This will keep calling itself with n-1, n-2...
// until the stack memory is completely exhausted.
countdown(n - 1);
}
int main() {
// This will eventually cause a crash/Stack Overflow.
countdown(10);
return 0;
}
Why it matters
In simple loops, an infinite cycle just makes your computer fan spin fast. In recursion, an infinite cycle is a fatal error because it consumes physical resources (memory) rather than just time. Every time you write a recursive function, your first priority must be visualizing the "exit door." If there is any path through your code that avoids the base case, your program is a ticking time bomb.
Key takeaway
Infinite recursion occurs when a function lacks a reachable base case, leading to a Stack Overflow crash as the program runs out of memory.