【发布时间】:2012-03-05 11:25:33
【问题描述】:
考虑一下这个简单的 C 程序
#include <stdio.h>
int func()
{
printf("Hello World\n");
return 0;
}
int main()
{
printf("Hello World\n");
return 0;
}
这是由 gcc 编译的对应的 32 位程序集
.file "a.c"
.section .rodata
.LC0:
.string "Hello World"
.text
.globl func
.type func, @function
func:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
movl $.LC0, (%esp)
call puts
movl $0, %eax
leave
ret
.size func, .-func
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl $.LC0, (%esp)
call puts
movl $0, %eax
leave
ret
.size main, .-main
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section .note.GNU-stack,"",@progbits
为什么 gcc 在函数 'func()' 中为字符串 "Hello World" 保留 24 个字节,而在主函数中为同一字符串保留 16 个字节?
【问题讨论】:
-
它与字符串没有任何关系,它永远不会被加载到堆栈上。主函数序言中的 $16 用于使堆栈指针对齐。注意 andl 指令。
-
Hans,你说的是 main 中的 andl 指令。它是将堆栈指针与页面边界对齐的 andl 指令。我在询问主函数中的 subl $16, (%esp) 和 func 中的 subl $24, (%esp)
标签: x86