简体   繁体   中英

How the local variable stored in stack

for the program, local variables are defined and allocated in stack, but, I just wonder the order in defining the local variables is not the same with the order using it. For example, in the main function, int abc is defined, as described, abc is allocated in stack, which means if variable a is located in the bottom of stack, but when variable is used first, how pop a out from the stack? Or ebp point to the location where all variables has been stored?

Essentially within a function, local variables are stored on a stack-frame. Within the stack-frame, the order of access of the variables can be random. I will recommend reading this: http://www.cs.uwm.edu/classes/cs315/Bacon/Lecture/HTML/ch10s07.html

Consider the following code

int main (void)
{
  int a = 1, b = 2, c = 3;

  c = c + 55;
  a = a + 10;

  return 0;
}

A compiler can generate the following code

main:
.LFB0:
        .cfi_startproc
        push    rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        mov     rbp, rsp
        .cfi_def_cfa_register 6
        mov     DWORD PTR [rbp-4], 1
        mov     DWORD PTR [rbp-8], 2
        mov     DWORD PTR [rbp-12], 3
        add     DWORD PTR [rbp-12], 55
        add     DWORD PTR [rbp-4], 10
        mov     eax, 0
        pop     rbp
        .cfi_def_cfa 7, 8
        ret
        .cfi_endproc

Note that the variable a , b and c are stored at location rbp-4 , rbp-8 and rbp-12 , therefore each variable gets 4 bytes (in my system). It is minus because the stack grows downward and the starting of the stack frame of this function is indicated by the contents of rbp .

Next, note that first c = c + 55 and then a = a + 10 does no push or pop operation, and just access the locations directly, using add DWORD PTR [rbp-12], 55 and add DWORD PTR [rbp-4], 10 respectively. The compiler will know where within a stack-frame these variables are.

Notice the push rbp before the variables are declared and accessed. This operation stored the present value of rbp (the base pointer, 64 bit), on the stack-frame. Next rbp is updated to get a new value indicating limits for this function. Now within this limit, all the local variables can be stored. Also note the pop rbp before the return. This restores the old value of rbp from the stack-frame, which was stored before, so that after ret , it can get back to the old state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM