stack changes when calling function in c

C code:

int f(int a, int b){ a=1; int variable1=2; int variable2=1; return 0; } int main() { f(1,2); return 0; }

Assembler code:

.file "test.c" .text .globl f .type f, @function f: pushl %ebp movl %esp, %ebp subl $16, %esp movl $1, 8(%ebp) movl $2, -8(%ebp) movl $1, -4(%ebp) movl $0, %eax leave ret .size f, .-f .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $8, %esp movl $2, 4(%esp) movl $1, (%esp) call f movl $0, %eax addl $8, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.1.2 20080704 (Red Hat 4.1.2-48)" .section .note.GNU-stack,"",@progbits

The important extraction that can make usknow about stack is:

In main: subl $8, %esp movl $2, 4(%esp) movl $1, (%esp) call f in f: pushl %ebp movl %esp, %ebp subl $16, %esp movl $1, 8(%ebp) movl $2, -8(%ebp) movl $1, -4(%ebp) movl $0, %eax leave ret

first of all, in function main, beforecalling function f, the instruction subtracts esp by 8 because there are 2parameters need to be passed into function f. when the two parameters arepassed into stack function f is called which will push the return address intostack.

Then in function f, the first thing need tobe done is save the previous stack base pointer by pushing it into stack andthen set the current stack pointer as base stack pointer of current function. Thefunction f uses epb to retrieve parameters passed into function f in the main.

The code declares two variables in the functionf which locates in the stack. We can see that the esp is subtracted by 16 toallocate a block of stack memory for storing variables. Here we just allocatetwo variables but the instruction allocates 16 bytes for us. It seems that 16bytes are the minimum size of stack memory that can be allocated in the stack.

Before return from function f the savedprevious stack base pointer need to be set back by poping the stack(popl %ebp).Last instruction ret in the function f will pop the return address saved in thestack and jump to that address.

So the major structure of the stack for theabove program is as follows:


stack changes when calling function in c_第1张图片

From the code we can use that ebp is usedto retrieve variable in the stack. It severs as a base pointer as its nameindicates.

In a nutshell, when a function is called in c, first of all, the parameters are passed into stack, then function return address, previous stack frame address, and other variables declared inside the function called.

你可能感兴趣的:(c,function,gcc,Parameters,structure,variables)