根据维基百科的说法:
调用方将返回地址推入堆栈,当被调用的子程序完成时,它会从调用堆栈中弹出返回地址,并将控制转移到该地址。
维基图片:
我不太理解这个。 假设我有一个 C 程序如下:
#include <stdio.h>
int foo(int x)
{
return x+1;
}
void spam()
{
int a = 1; //local variable
int b = foo(a); //subroutine called
int c = b; //local variable
}
int main()
{
spam();
return 0;
}
我认为调用栈应该像下面的图示一样:
<None> means none local variables or params
_| parameters for foo() <int x> |_
top | local of spam() <int c> |
^ | return address of foo() |<---foo() called, when finishes, return here?
| | local of spam() <int b> |
bot | local of spam() <int a> |
_| parameters for spam() <None> |_
| locals of main() <None> |
| return address of spam() |<---spam() called, when finishes, return here?
| parameters for main() <None> |
问题:
根据从Wiki引用的话,
被调用的子程序在结束时会从调用栈中弹出返回地址,并将控制权转移至该地址。
1.我的图示正确吗?
2.如果我的图示正确,那么当foo()结束时,它将会
从调用栈中弹出返回地址并将控制权转移到该地址
,但是它如何能够弹出返回地址呢? 因为当foo结束时,当前的堆栈指针指向spam的本地变量,对吗?
更新:
如果main()看起来像这样:
int main()
{
spam();
foo();
}
那么调用栈应该是什么样子的?