如何从堆栈访问函数局部变量? [英] How are the function local variables accessed from the stack?
问题描述
从 http://www.learncpp。 com / cpp-tutorial / 79-the-stack-and-the-heap /
当函数
被调用时发生:
- 超出函数调用的指令地址被推入堆栈。这是CPU在
函数返回后要记住的地方。
- 房间是在函数的返回类型的栈上。
- 当前的堆栈顶部保存在特殊的指针
- 在此点之后添加到堆栈中的所有内容都被视为函数的本地。
- 所有函数参数
- 函数中的指令开始执行。
- 局部变量被推入堆栈,
我不知道第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:
- 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.
- Room is made on the stack for the function’s return type. This is just a placeholder for now.
- The CPU jumps to the function’s code.
- The current top of the stack is held in a special pointer called the stack frame.
- Everything added to the stack after this point is considered "local" to the function.
- All function arguments are placed on the stack.
- The instructions inside of the function begin executing.
- 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屋!