In this lesson, you will learn why deep recursion can crash your Rust program and how stack frames interact with function calls.
The Cost of a Call
Every time you call a function in Rust, the computer allocates a small chunk of memory called a stack frame. This frame stores the function’s local variables, arguments, and the "return address" (where to go back to once the function finishes).
The stack is a fixed-size region of memory. Because your program has a finite amount of space for these frames, you cannot nest them infinitely.
Recursive Dangers
Recursion happens when a function calls itself. If a recursive function doesn't have a solid "base case" to stop the execution, or if it simply runs too many times, it will keep pushing new stack frames onto the memory stack until it runs out of space. This is a Stack Overflow.
Consider this simple, dangerous example:
fn count_to_infinity(n: u32) {
// This lacks a base case,
// and will eventually crash the program!
count_to_infinity(n + 1);
}
Even if you do have a base case, like calculating a factorial of a massive number, the sheer depth of the recursion can exhaust the stack:
fn factorial(n: u64) -> u64 {
if n == 0 { 1 }
else { n * factorial(n - 1) }
}
If n is large enough, the chain of factorial calls will create thousands of stack frames. Eventually, the program attempts to write to a memory address outside the allocated stack boundaries, triggering an immediate crash to ensure memory safety.
Identifying the Pattern
To prevent this, look for recursive functions that don't have a clear, reachable exit condition. Furthermore, even with an exit condition, be wary of "deep" recursion where the number of calls depends on user input or large datasets.
If your logic requires thousands of iterations, the stack is the wrong tool. In such cases, you are better off using iterative loops, which reuse the same stack frame over and over rather than nesting them.
Key Takeaway: Each recursive call consumes a finite stack frame; deep or uncontrolled recursion will exceed your stack capacity and cause a program crash.