Analysis of the creation and destruction of function stack frames and variables

Function call process
Each function call has a process. During this period, a stack space is opened up for the function, which is used for saving and on-site protection of temporary variables of this function call.
Function stack frame The stack space opened up for a function during a
function call is called a function stack frame.
Analyze the function stack frame with an example:

#include<stdio.h>

int Add(int x, int y)
{
    int z = 0;
    z = x + y;
    return z;
}

int  main()
{
    int a = 1;
    int b = 2;
    int ret = 0;
    ret = Add(a, b);
    printf("%d\n", ret);
    return 0;

}

Analysis process (pictured below):
1) The main function is called in the __tmainCRTStartup function, so before the main function creates the stack frame, there is also the function stack frame of _tmainCRTStartup (not detailed here);
2) The maintenance of the stack frame Two registers are needed to store the stack bottom pointer and the stack top pointer, namely ebp (stack bottom pointer) and esp (stack top pointer);
3) The rules for popping and stacking are FIFO, LIFO;
4) main When a function creates a stack frame, it is mainly divided into several steps: push the stack, open up space, initialize the space, and create local variables;
5) The next step is the calling process of the function, including: passing parameters, entering the Add function, Create the stack frame of the Add function, and also have several steps such as pushing the stack, opening up space, initializing the space, and creating local variables;
6) For the return of the function, the last-in-first-out rule is guaranteed when popping the stack, so the Add function is performed first. Pop the stack, bringing the requested value back through the register.

1. The creation of the main function stack frame and the creation of local variables:

write picture description here

2. The actual parameter is passed to the formal parameter:

write picture description here

3. Inside the Add function:

write picture description here

4. Function return

write picture description here

5. The pop-up inside the main function is the same as the pop-up rule of the Add function, and it is not drawn here.

Note: The picture is drawn from the bottom to the top. Do not read it wrong when reading. If there are any shortcomings, please make valuable suggestions.
Attach the whole process diagram.

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805608&siteId=291194637