栈上的变量是如何访问的?

发布于 2024-07-13 20:49:45 字数 343 浏览 5 评论 0原文

假设我们有这些局部变量:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

祁梦 2024-07-20 20:49:45

堆栈上的局部变量通常是相对于所谓的帧指针来访问的,该指针指向堆栈帧的开头。 也可以相对于堆栈指针来执行此操作,但由于堆栈指针在表达式求值期间四处移动,因此更难以跟踪。

实际上,这些变量也可以保存在处理器寄存器中。

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.

紧拥背影 2024-07-20 20:49:45

或者我错过了什么

你错过了堆栈驻留在常规内存中,它允许随机访问 - 只需将适当的偏移量添加到帧指针(“本地”堆栈的底部),你就会得到一个指向内存单元的指针保持价值。

Or am I missing something

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.

帅气称霸 2024-07-20 20:49:45

这是否意味着为了获得
a 的值、d、c 的值和
b 必须首先弹出
堆栈?

发出的代码只是在进入函数时将堆栈指针移动正确的字节数。 当离开该功能时,它将向后移动相同的距离。 因此,它不会单独弹出变量。 假设 int 是 4 个字节,您给出的示例会将堆栈指针移动 16 个字节。 由于堆栈帧中的其他信息(例如返回地址),它实际上将其移动得更远。

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?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文