#include <stdio.h>
int func (int param1, int param2,int param3) {int var1 = param1; int var2 = param2; int var3 = PARAM3; printf ("var1=%d,var2=%d,var3=%d", VAR1,VAR2,VAR3); return var1; int main (int argc, char* argv[]) {int result = func (1,2,3); return 0; }
First, the variable distribution in the stack is distributed from a high address to a low address, and EBP is a pointer to the bottom of the stack, unchanged in the procedure call, also known as a frame pointer. ESP points to the top of the stack, moves when the program executes, ESP reduces the allocation space, ESP increases the free space, and ESP is called the stack pointer.
The following step is to parse the call procedure for a function
1. Function main execution, main parameters from right to left to step into the stack, and finally press into the return address
2. Perform line 15th, 3 parameters are pressed into the stack from Left-to-right order, and from Param3 to param1, the stack is distributed as follows:
3. Then the return address into the stack: at this time the stack is distributed as follows:
4. The 3rd line function call, through the jump instruction into the function, after the function address into the stack, ebp into the stack, and then the current ESP value to EBP, the corresponding assembly instructions:
Push EBP
mov ebp ESP
At this time the stack top and the bottom of the stack point to the same position, the stack is distributed as follows:
5. Line 5th begins execution, int var1 = param1; int var2 = param2; int VAR3 = param3, stored sequentially in declared order. The corresponding assembly:
mov 0x8 (%EBP),%eax
mov%eax,-0x4 (%EBP)
It assigns the contents of the [ebp+0x8] address to the EAX, which assigns the Param value to the eax, and then places the EAX value in the address of [EBP-4], which assigns the EAX value to the VAR1, completes the c code int var1 = param1, and the other variables are identical.
6. Line 9th, output results, line 10th executes the corresponding assembly code:
mov -0x4 (%EBP),%eax
Finally, the return value of the function is saved through the EAX register.
7. Call execution function completed, local variable var3,var2,var1 a stack, EBP restore the original value, return to the address stack, find the original execution address, param1,param2,param3 sequentially out of the stack, function call execution completed