【发布时间】:2011-11-21 13:38:31
【问题描述】:
根据维基:
调用者将返回地址压入栈中,被调用者 子程序,当它完成时,从调用中弹出返回地址 堆栈并将控制权转移到该地址。
图片来自维基:
我不太明白这个。 假设我有一个 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> |
问题:
根据维基引用的话,
被调用的子程序,当它完成时,弹出返回地址 调用堆栈并将控制权转移到该地址。
1.我的画对吗?
2.如果是对的,那么当 foo() 结束时,它会
从调用堆栈中弹出返回地址并将控制权转移到 那个地址
,但是它怎么能弹出返回地址呢? 因为当 foo 完成时,当前堆栈指针指向垃圾邮件的本地, 对吧?
更新:
如果 main() 看起来像这样会怎样:
int main()
{
spam();
foo();
}
那么调用栈应该是什么样子的呢?
【问题讨论】: