The stack structure of function call

Source: Internet
Author: User

The stack structure of the function call process was previously known until Tuesday, when a colleague from the technical salon made a different point of view and was unable to answer it.

The test code is as follows:

intAddintAintb) {    inti = A +b; returni;}intFuncintAintb) {    returnAdd (3, 5); }intMain () {intA = func (3,5); return 0;}

Linux generates the assembly code as follows:

Add:.LFB0:. Cfi_startproc PUSHL%ebp; save Ebp. Cfi_def_cfa_offset8. Cfi_offset5, -8movl%esp,%EBP; esp points to the bottom of the stack. Cfi_def_cfa_register5Subl $ -,%esp; reserved stack space movl A(%EBP),%eax movl8(%EBP),%edx addl%edx,%eax movl%eax,-4(%EBP) MOVL-4(%EBP),%eaxleave; see Assembly instruction explanation. Cfi_restore5. CFI_DEF_CFA4,4    retSee assembly instruction explanation. Cfi_endproc.LFE0:. SizeAdd, .-Add. globl func. Type func, @functionfunc:.LFB1:. Cfi_startproc PUSHL%ebp; ebp into the stack. Cfi_def_cfa_offset8. Cfi_offset5, -8movl%esp,%EBP; esp points to the bottom of the stack. Cfi_def_cfa_register5Subl $8,%esp MOVL $5,4(%ESP) MOVL $3, (%ESP)Pager    Add, return the address into the stack and jump to add    Leave. Cfi_restore5. CFI_DEF_CFA4,4    ret. Cfi_endproc.LFE1:. Size func,.-func. GLOBL Main. Type Main, @function

A compilation of several instructions explains:

Call

Push EIP

jmp

Leave

MOV ESP,EBP

Pop EBP

Ret:

Pop EIP

Add esp,4

Pop EIP:

mov EIP, [ESP]

Add esp,4

Stack structure diagram:

————————————

Ebp

Local variable

5; Func Stack Frames

3

return address

————————————

EBP; Save the func ebp

Local variable

————————————

The stack structure of function call

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.