How are the function local variables accessed from the stack?

后端 未结 3 498
野性不改
野性不改 2021-02-08 06:49

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:

3条回答
  •  心在旅途
    2021-02-08 07:22

    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.

提交回复
热议问题