c语言中栈的分配(挖个坑)

来源:互联网 发布:房子夕晒软件 编辑:程序博客网 时间:2024/06/03 21:27

大家都知道在c语言的运行过程中,局部变量都是存放在栈中的,且是从高位到低位进行进行空间分配。

但是最近遇到一个程序还是让我有点小困惑。

先看一个程序。



很明显,地址从高到低分配,和预计的一样。

稍微修改一下,再运行。




很明显,从低位到高位!!!

明确一下问题:栈区会应为局部变量的占内存的大小更改内存的分配方式。

为什么?为什么?为什么?


用-S生成汇编语言看一下

第一种情况的汇编语言

.file"main.c".section.rodata.LC0:.string"Address s = Ox%x\n".LC1:.string"Address d = Ox%x\n".text.globlmain.typemain, @functionmain:.LFB0:.cfi_startprocpushl%ebp.cfi_def_cfa_offset 8.cfi_offset 5, -8movl%esp, %ebp.cfi_def_cfa_register 5andl$-16, %espsubl$32, %espmovl%gs:20, %eaxmovl%eax, 28(%esp)xorl%eax, %eaxmovl$6513249, 24(%esp)movw$25185, 21(%esp)movb$0, 23(%esp)leal24(%esp), %eaxmovl%eax, 4(%esp)movl$.LC0, (%esp)callprintfleal21(%esp), %eaxmovl%eax, 4(%esp)movl$.LC1, (%esp)callprintfmovl$1, %eaxmovl28(%esp), %edxxorl%gs:20, %edxje.L3call__stack_chk_fail.L3:leave.cfi_restore 5.cfi_def_cfa 4, 4ret.cfi_endproc.LFE0:.sizemain, .-main.ident"GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3".section.note.GNU-stack,"",@progbits


第二种情况的汇编语言

.file"main.c".section.rodata.LC0:.string"Address s = Ox%x\n".LC1:.string"Address d = Ox%x\n".text.globlmain.typemain, @functionmain:.LFB0:.cfi_startprocpushl%ebp.cfi_def_cfa_offset 8.cfi_offset 5, -8movl%esp, %ebp.cfi_def_cfa_register 5andl$-16, %espsubl$32, %espmovl%gs:20, %eaxmovl%eax, 28(%esp)xorl%eax, %eaxmovl$6513249, 17(%esp)movl$1684234849, 21(%esp)movw$26213, 25(%esp)movb$0, 27(%esp)leal17(%esp), %eaxmovl%eax, 4(%esp)movl$.LC0, (%esp)callprintfleal21(%esp), %eaxmovl%eax, 4(%esp)movl$.LC1, (%esp)callprintfmovl$1, %eaxmovl28(%esp), %edxxorl%gs:20, %edxje.L3call__stack_chk_fail.L3:leave.cfi_restore 5.cfi_def_cfa 4, 4ret.cfi_endproc.LFE0:.sizemain, .-main.ident"GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3".section.note.GNU-stack,"",@progbits



在前面的几句mov有很明显的不同,一个是从低到高分配,一个是从高到低分配.


猜想:编译器对语言进行的优化,让长的字符串先进栈。


但为什么要这么做呢?

求解答。