What happens to stack Frames when main() calls main()
-
13-07-2021 - |
Question
Please consider the following code:
#include <stdio.h>
int main()
{
static int counter=5;
printf ("Counter = %d\n", counter);
if (counter--)
{
main();
}
return 0;
}
Compile:
gcc test.c -ansi -Wall –pedantic
Execute:
[root@mars home]# ./a.out
Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1
Counter = 0
Here main() is calling itself().
It seems that main()
function's original stackframe will be overwritten each time main()
is called by itself.
But what will be the return address? Can a function return to its own stackframe?
Please help me clarify this doubt.
Thanks.
Solution
No it is not overwritten. It is a normal function call (in this case recursive). You are probably confused by your counter
variable. This variable is declared static, which means that it is initialized only once, so the line below is "executed" only once:
static int counter=5;
In other words you can think of your counter
as if it was a global variable initialized only once (with the value 5). In each invokation of main
it is decremented until it reaches zero. After that happens all the main
functions return, so the stack is unwinded
(as in normal function call which it is).
OTHER TIPS
This is quite normal in many computer languages, and is called 'recursion'. A new stack frame is created for each invocation of the function so there is no overwriting.
The return address of the outer main() is the runtime library as usual. The return address of the inner main() is the outer main().
The one thing that muddies the waters in your example is that you declared counter as static. That means it is allocated on the heap in the data segment rather than on the stack (as explained by alk in the comment), so each invocation of main() shares the same instance of counter.
Short answer: It's a simple case of recursion. So it will allocate new stack frames & not overwrite previous frame.
Long answer:
What happens to stack Frames when main() calls main():
C doesn't differentiate main from any other function. It's a simple, normal case of recursion.
'main' is special ONLY because, the default crt0.asm that came with the compiler (or whatever its name is in your compiler) calls main after its basic initialization (like stack pointer, etc) is done.
Apart from this difference, there is nothing, in which main is special.