栈上的变量是如何访问的?
假设我们有这些局部变量:
int a = 0;
int b = 1;
int c = 2;
int d = 3;
据我所知,这些变量将在系统堆栈上分配,如下所示:
| |
| 3 | d
| 2 | c
| 1 | b
|_0_| a
这是否意味着为了获取 a 的值,必须首先弹出 d、c 和 b 的值出栈? 如果是这样,这些值去了哪里? 这是否意味着访问最近声明的变量会更快? 或者我是否遗漏了一些东西(我怀疑是这样),而整个事情以其他方式运作?
编辑:谢谢大家!
Suppose we have these local variables:
int a = 0;
int b = 1;
int c = 2;
int d = 3;
As far as I know, these will be allocated on the system stack, like this:
| |
| 3 | d
| 2 | c
| 1 | b
|_0_| a
Does this mean that in order to get the value of a, the values of d, c and b must first be popped out of the stack? If so, where do these values go? Does this mean that accessing more recently declared variables will be faster? Or am I missing something (which I suspect is the case), and the whole thing works in some other way?
EDIT: thanks, guys!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
堆栈上的局部变量通常是相对于所谓的帧指针来访问的,该指针指向堆栈帧的开头。 也可以相对于堆栈指针来执行此操作,但由于堆栈指针在表达式求值期间四处移动,因此更难以跟踪。
实际上,这些变量也可以保存在处理器寄存器中。
The local variables on the stack are usually accessed relative to the so-called frame pointer, which points at the start of your stack frame. It would also be possible to do this relative to the stack pointer, but since this moves around during evaluation of expressions it is more difficult to keep track of.
In practice such variables may also be kept in processor registers.
你错过了堆栈驻留在常规内存中,它允许随机访问 - 只需将适当的偏移量添加到帧指针(“本地”堆栈的底部),你就会得到一个指向内存单元的指针保持价值。
You're missing that the stack resides in regular memory, which allows random access - just add the appropriate offset to the frame pointer (the bottom of the 'local' stack) and you get a pointer to the memory cell holding the value.
发出的代码只是在进入函数时将堆栈指针移动正确的字节数。 当离开该功能时,它将向后移动相同的距离。 因此,它不会单独弹出变量。 假设 int 是 4 个字节,您给出的示例会将堆栈指针移动 16 个字节。 由于堆栈帧中的其他信息(例如返回地址),它实际上将其移动得更远。
The code emitted simply moves the stack pointer the correct number of bytes when entering the function. It moves it back the same distance when leaving the function. Thus, it does not pop off the variables individually. Assuming an int is 4 bytes, the example you gave would move the stack pointer 16 bytes. It actually moves it further than this because of other information in the stack frame such as the return address.