函数调用时入栈参数与局部变量在栈中地址问题
#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个字节装的是什么?
求教大神们。
...全文
相关推荐
C语言函数调用分析总结
C语言是一个强大的语言,特别是对于嵌入式开发过程中有时需要反汇编分析代码中存在的问题,函数是C语言中的难点,关于函数的调用也是很多人不能理解的,很多知道的也是一知半解。对C语言的调用有了一个比较清晰的认识就能够更清晰的分析代码中存在的问题。我也是看了很多的资料,然后自己写了一一段小代码作为分析的测试代码。
C函数调用过程原理及函数栈帧分析 - 编程之道 - SegmentFault 思否1
1. x86 Instruction Set Reference 2. x86 Disassembly/Functions and Stack Frames 3
C语言函数调用栈(一) - clover_toeic - 博客园1
C语言函数调用栈(一) - clover_toeic - 博客园1
栈帧理解_19_7_191
(2)函数调用深度 在很多系统中都对函数调用的深度做了限制,函数调用深度是指函数嵌套的程度 (3)函数调用的参数 栈帧部分已经描述了函数参数的保存位
函数调用的基本原理
编程中有时会遇到一个系统异常java.lang.StackOverflowError,栈溢出错误,要理解这个错误,我们需要理解函数调用的实现机制,本文就谈谈它的基本原理 ...


其它技术问题
