How are the function local variables accessed from the stack?
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:
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.
No they are not. The stack pointer (typically the esp
registry) points to a
, esp+8h
points to b
, esp+16h
points to c
and so on. There's no need for a
to be popped.
Note that this is an implementation detail. You shouldn't worry about these. The number I've given is purely theoretical, on some architectures descending addresses are given to latter parameters, on others the other way around. There's no guarantee this happens.
EDIT: It seems to me like that's not a very reliable source of information. It speaks of stack and heap, but these are implementation details, and might not even be there.
There's no constraint in the standard for anything to be implemented via a stack either. For example, I have the following code generated:
void foo(int x, int y, int z)
{
01241380 push ebp
01241381 mov ebp,esp
01241383 sub esp,0CCh
01241389 push ebx
0124138A push esi
0124138B push edi
0124138C lea edi,[ebp-0CCh]
01241392 mov ecx,33h
01241397 mov eax,0CCCCCCCCh
0124139C rep stos dword ptr es:[edi]
int c = x;
0124139E mov eax,dword ptr [x]
012413A1 mov dword ptr [c],eax
c = y;
012413A4 mov eax,dword ptr [y]
012413A7 mov dword ptr [c],eax
c = z;
012413AA mov eax,dword ptr [z]
012413AD mov dword ptr [c],eax
}
012413B0 pop edi
012413B1 pop esi
012413B2 pop ebx
012413B3 mov esp,ebp
012413B5 pop ebp
So you see, there's no stack there. The runtime has direct access to the elements: dword ptr [x]
, etc.
它使用堆栈指针和相对地址来指出c。
链接地址: http://www.djcxy.com/p/80370.html上一篇: 基于虚拟机的函数调用/返回实现问题
下一篇: 函数局部变量如何从堆栈中访问?