函数调用时入栈参数与局部变量在栈中地址问题

Dinghow9 2017-04-10 07:02:35
#include <iostream>

int foo(int a, int b, int c, int d) {
int e;
int f;
std::cout << std::hex;
std::cout << "a = " << a << std::endl;
std::cout << "Address of a: " << &a << std::endl;
std::cout << "Address of b: " << &b << std::endl;
std::cout << "Address of c: " << &c << std::endl;
std::cout << "Address of d: " << &d << std::endl;
std::cout << "Address of e: " << &e << std::endl;
std::cout << "Address of f: " << &f << std::endl;
// a 参数控制递归调用次数
if (a != 0) {
foo(a - 1, b, c, d);
}
return a + b + c + d;
}

int main() {
// 进行 4 次嵌套的函数调用
foo(4, 2, 3, 4);
return 0;
}

源码如上,运行结果
gcc 4.9.2 -32bit release:
a = 4
Address of a: 0x6efea0
Address of b: 0x6efea4
Address of c: 0x6efea8
Address of d: 0x6efeac
Address of e: 0x6efe8c
Address of f: 0x6efe88
a = 1
Address of a: 0x6efe70
Address of b: 0x6efe74
Address of c: 0x6efe78
Address of d: 0x6efe7c
Address of e: 0x6efe5c
Address of f: 0x6efe58
a = 2
Address of a: 0x6efe40
Address of b: 0x6efe44
Address of c: 0x6efe48
Address of d: 0x6efe4c
Address of e: 0x6efe2c
Address of f: 0x6efe28
a = 1
Address of a: 0x6efe10
Address of b: 0x6efe14
Address of c: 0x6efe18
Address of d: 0x6efe1c
Address of e: 0x6efdfc
Address of f: 0x6efdf8
a = 0
Address of a: 0x6efde0
Address of b: 0x6efde4
Address of c: 0x6efde8
Address of d: 0x6efdec
Address of e: 0x6efdcc
Address of f: 0x6efdc8
gcc 4.9.2 -64bit release:
a = 4
Address of a: 0x70fe30
Address of b: 0x70fe38
Address of c: 0x70fe40
Address of d: 0x70fe48
Address of e: 0x70fe0c
Address of f: 0x70fe08
a = 3
Address of a: 0x70fde0
Address of b: 0x70fde8
Address of c: 0x70fdf0
Address of d: 0x70fdf8
Address of e: 0x70fdbc
Address of f: 0x70fdb8
a = 2
Address of a: 0x70fd90
Address of b: 0x70fd98
Address of c: 0x70fda0
Address of d: 0x70fda8
Address of e: 0x70fd6c
Address of f: 0x70fd68
a = 1
Address of a: 0x70fd40
Address of b: 0x70fd48
Address of c: 0x70fd50
Address of d: 0x70fd58
Address of e: 0x70fd1c
Address of f: 0x70fd18
a = 0
Address of a: 0x70fcf0
Address of b: 0x70fcf8
Address of c: 0x70fd00
Address of d: 0x70fd08
Address of e: 0x70fccc
Address of f: 0x70fcc8
而就我目前的知识了解,栈是从高地址到底地址存储数据,而读取参数的顺序为从右到左,以第一次函数调用为例,入栈顺序应该是:d-c-b-a之后是按顺序将局部变量入栈,即e-f,但是比较e和f的地址可以发现二者在32位下相差14个字节,在64位下相差36个字节,感到比较奇怪,按之前看到的文章:http://blog.csdn.net/tdgx2004/article/details/5985531,在局部变量与参数之间应该是函数地址与保护栈底(32位下8个字节),但是实际情况是14个字节,非常好奇还有6个字节装的是什么?
求教大神们。
...全文
1008 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-04-11
  • 打赏
  • 举报
回复
调用约定 https://msdn.microsoft.com/zh-cn/magazine/9b372w95.aspx http://edu.csdn.net/course/detail/2344 C语言指针与汇编内存地址-一.代码要素 http://edu.csdn.net/course/detail/2455 C语言指针与汇编内存地址-二.函数
Dinghow9 2017-04-11
  • 打赏
  • 举报
回复
【错误更正】是用a的地址减去e的地址相差14
xskxzr 2017-04-10
  • 打赏
  • 举报
回复
相差14个字节是怎么算出来的?

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧