如何从堆栈访问函数局部变量? [英] How are the function local variables accessed from the stack?

查看:129
本文介绍了如何从堆栈访问函数局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.learncpp。 com / cpp-tutorial / 79-the-stack-and-the-heap /


当函数
被调用时发生:


  1. 超出函数调用的指令地址被推入堆栈。这是CPU在
    函数返回后要记住的地方。

  2. 房间是在函数的返回类型的栈上。




  3. 当前的堆栈顶部保存在特殊的指针

  4. 在此点之后添加到堆栈中的所有内容都被视为函数的本地。

  5. 所有函数参数
  6. 函数中的指令开始执行。

  7. 局部变量被推入堆栈,

我不知道第6点的工作原理。如果所有的函数参数都放在栈上,它们是如何被访问的?



如果例如,有三个参数 a b c ,并从顶部放置在堆栈上

  | a | 
| b |
| c
| |
...
| ___ |

现在,当函数要访问 c ?是否 a b 弹出?

解决方案

堆栈是一个隐喻堆栈。请记住它仍然是一个RAM ,所以如果你知道你在找什么,你可以访问每个地址,而不弹出其他。



自动变量的大小在编译时已知 - 编译器为每个变量标记 offset ,偏移量由堆栈中自动变量部分start [或栈的头,都是有效的,具体的实现依赖于架构],它只需要访问它们: start + offset 为每个变量的偏移量。


From http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

Here is the sequence of steps that takes place when a function is called:

  1. The address of the instruction beyond the function call is pushed onto the stack. This is how the CPU remembers where to go after the function returns.
  2. Room is made on the stack for the function’s return type. This is just a placeholder for now.
  3. The CPU jumps to the function’s code.
  4. The current top of the stack is held in a special pointer called the stack frame.
  5. Everything added to the stack after this point is considered "local" to the function.
  6. All function arguments are placed on the stack.
  7. The instructions inside of the function begin executing.
  8. Local variables are pushed onto the stack as they are defined.

I am not sure how point #6 works. If all function arguments are placed on the stack, how are they accessed?

If for example, there are three arguments a, b and c and are placed on stack like this from top

| a |
| b |
| c |
|   |
 ...
|___|

Now what happens when the function wants to access c? Are a and b popped out?

解决方案

The stack is a metaphoric stack. Remember it is still a RAM, so you can access each address without popping the rest, if you know what you are looking for.

Since the automatic variable's size is known at compile time - the compiler marks offset for each variable, the offset is determined from where the automatic variables section on stack start [or the stack's head, both are valid and the specific implementation depends might depend on architecture], and it access them by merely: start + offset for each variable's offset.

这篇关于如何从堆栈访问函数局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆