当main()调用main()时堆栈帧会发生什么

San*_*ngh 3 c program-entry-point stack-frame

请考虑以下代码:

#include <stdio.h>

int main()
{
    static int counter=5;

    printf ("Counter = %d\n", counter);

    if (counter--)
    {
        main();
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译:

gcc test.c -ansi -Wall –pedantic
Run Code Online (Sandbox Code Playgroud)

执行:

[root@mars home]# ./a.out 
Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1
Counter = 0
Run Code Online (Sandbox Code Playgroud)

这里main()调用自己().

似乎main()每次main()调用函数的原始堆栈帧时都会被覆盖.

但回信地址是什么?函数可以返回自己的堆栈框架吗?

请帮我澄清这个疑问.

谢谢.

sir*_*rge 6

不,它不会被覆盖.这是一个正常的函数调用(在这种情况下是递归的).您可能会对您的counter变量感到困惑.此变量声明为static,这意味着它只初始化一次,因此下面的行只"执行"一次:

static int counter=5;
Run Code Online (Sandbox Code Playgroud)

换句话说,您可以将您想象为counter仅仅初始化一次的全局变量(值为5).在每次调用中,main它会递减直到达到零.在那之后,所有main函数都返回,因此堆栈就是unwinded(正常函数调用中).