An in depth analysis of variable types in c++ from assembly

  • 2020-04-01 23:33:40
  • OfStack

The lifetime and visibility of global variables is the duration of the program, so let's take a look at the assembly in action:

C + + source code:


int i = 2;//The global variable
int main() {
    int j = i;
}

Here is the assembly code:


PUBLIC    ?i@@3HA                        ; i
_DATA    SEGMENT
?i@@3HA    DD    02H                    ;  The global variable i Memory space 
_DATA    ENDS
PUBLIC    _main
; Function compile flags: /Odtp
; File c:usersadministratordesktopc++testa.cpp
_TEXT    SEGMENT
_j$ = -4                        ; size = 4
_main    PROC
; 3    : int main() {
    push    ebp
    mov    ebp, esp
    push    ecx; Assign to local variables 4 Byte storage area 
; 4    :     int j = i;
    mov    eax, DWORD PTR ?i@@3HA            ;  Get global variables i The value of the 
    mov    DWORD PTR _j$[ebp], eax;eax entities i And assign it to a local variable j
; 5    : }
    xor    eax, eax
    mov    esp, ebp;//Stack top pointer restores, freeing the stack space allocated for j
    pop    ebp
    ret    0
_main    ENDP
_TEXT    ENDS

From the assembly language, we can see that the memory of the global variable I is allocated in the data area of memory (specified by _DATA), so it is always present during the program running, so all parts of the program can be accessed, and it is destroyed as the program ends. While the memory of local variable j is dynamically allocated on the stack in the running main function, and after the main function ends, this space is freed, so the local variable j cannot be accessed outside the main function.

In fact, when the operating system loads the executable, it first loads the data in the data area into the appropriate memory before it starts to run the program, so global variables are generated after the file is loaded but before the first program language is executed.


Related articles: