您似乎正在使用 GNU 汇编器和 GCC 的 C 库来构建您的可执行文件。您的代码的主要问题是您在使用它之前没有设置寄存器 %ebp。通常使用C,您的函数首先设置本地堆栈帧,其中包括初始化%ebp。要正确设置本地堆栈帧,并在返回之前清理堆栈,您可以使用如下代码:
.section .data
digitformatstr:
.string "%d\n"
.section .text
.global main
main:
push %ebp /* setup local stack frame */
mov %esp, %ebp
push $1337
pop %eax
movl %eax, -4(%ebp)
push -4(%ebp)
push $digitformatstr
call printf
addl $8, %esp
leave /* remove local stack frame */
ret
堆栈帧和 32 位 C 调用约定的初学者指南可以在 here 找到。
关于您的代码的另一条评论。你这样做:
push $1337
pop %eax
movl %eax, -4(%ebp)
push -4(%ebp)
push $digitformatstr
call printf
我不确定你想用这段代码做什么。几乎看起来您试图将 1337 作为局部变量放在堆栈上(但尚未在堆栈上为局部变量分配空间)。由于您似乎试图简单地调用printf,其中第二个参数是一个整数,因此您应该将该值(1337)压入堆栈。上面的所有代码都应该是:
push $1337 /* 2nd argument to printf */
push $digitformatstr /* 1st argument to printf */
call printf /* call printf
main 的最终清理代码可能类似于:
main:
push %ebp /* setup local stack frame */
mov %esp, %ebp
push $1337 /* 2nd argument to printf */
push $digitformatstr /* 1st argument to printf */
call printf /* call printf
addl $8, %esp /* cleanup the 2 32 bit arguments */
/* we pushed on the stack */
leave /* remove local stack frame */
ret