We've all heard the term "Stack Overflow," but today I visualized what it actually means.
When a function calls itself (Recursion), it doesn't just "loop." The computer actually pauses the current function, packages up all the variables, and pushes a new Stack Frame onto memory.
-
Frame 1:
n = 3(Paused) -
Frame 2:
n = 2(Paused) -
Frame 3:
n = 1(Running)
If you recurse too deep without stopping, you run out of Stack memory. Boom. Stack Overflow.
The Code
This program prints the memory address of the local variable n during each recursive call. You will see the addresses moving down in memory, proving that each call creates a new, distinct stack frame.
// Day 8: Visualizing Stack Frames
#include <stdio.h>
void recursive_print(int n) {
// Base case: Stop when n hits 0
if (n == 0) {
printf("Base case reached. Popping stack now...\n");
return;
}
// Print the address of 'n' to see the stack grow
// Notice the addresses get smaller (Stack grows DOWN)
printf("Frame %d | Address of n: %p\n", n, (void*)&n);
// Recursive step: Call itself with n-1
recursive_print(n - 1);
printf("Returning from Frame %d\n", n);
}
int main() {
recursive_print(3);
return 0;
}
📂 View the source code on GitHub:https://github.com/Ujjawal0711/30-Days
Top comments (0)