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

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

先看一个程序。



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

稍微修改一下,再运行。




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

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

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


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

第一种情况的汇编语言

	.file	"main.c" 	.section	.rodata .LC0: 	.string	"Address s = Ox%x\n" .LC1: 	.string	"Address d = Ox%x\n" 	.text 	.globl	main 	.type	main, @function main: .LFB0: 	.cfi_startproc 	pushl	%ebp 	.cfi_def_cfa_offset 8 	.cfi_offset 5, -8 	movl	%esp, %ebp 	.cfi_def_cfa_register 5 	andl	$-16, %esp 	subl	$32, %esp 	movl	%gs:20, %eax 	movl	%eax, 28(%esp) 	xorl	%eax, %eax 	movl	$6513249, 24(%esp) 	movw	$25185, 21(%esp) 	movb	$0, 23(%esp) 	leal	24(%esp), %eax 	movl	%eax, 4(%esp) 	movl	$.LC0, (%esp) 	call	printf 	leal	21(%esp), %eax 	movl	%eax, 4(%esp) 	movl	$.LC1, (%esp) 	call	printf 	movl	$1, %eax 	movl	28(%esp), %edx 	xorl	%gs:20, %edx 	je	.L3 	call	__stack_chk_fail .L3: 	leave 	.cfi_restore 5 	.cfi_def_cfa 4, 4 	ret 	.cfi_endproc .LFE0: 	.size	main, .-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 	.globl	main 	.type	main, @function main: .LFB0: 	.cfi_startproc 	pushl	%ebp 	.cfi_def_cfa_offset 8 	.cfi_offset 5, -8 	movl	%esp, %ebp 	.cfi_def_cfa_register 5 	andl	$-16, %esp 	subl	$32, %esp 	movl	%gs:20, %eax 	movl	%eax, 28(%esp) 	xorl	%eax, %eax 	movl	$6513249, 17(%esp) 	movl	$1684234849, 21(%esp) 	movw	$26213, 25(%esp) 	movb	$0, 27(%esp) 	leal	17(%esp), %eax 	movl	%eax, 4(%esp) 	movl	$.LC0, (%esp) 	call	printf 	leal	21(%esp), %eax 	movl	%eax, 4(%esp) 	movl	$.LC1, (%esp) 	call	printf 	movl	$1, %eax 	movl	28(%esp), %edx 	xorl	%gs:20, %edx 	je	.L3 	call	__stack_chk_fail .L3: 	leave 	.cfi_restore 5 	.cfi_def_cfa 4, 4 	ret 	.cfi_endproc .LFE0: 	.size	main, .-main 	.ident	"GCC: (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3" 	.section	.note.GNU-stack,"",@progbits



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


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


但为什么要这么做呢?

求解答。