【发布时间】:2019-09-30 12:02:06
【问题描述】:
我正在尝试链接 x86 程序集和 C。
我的 C 程序:
extern int plus_10(int);
# include <stdio.h>
int main() {
int x = plus_10(40);
printf("%d\n", x);
return 0;
}
我的汇编程序:
[bits 32]
section .text
global plus_10
plus_10:
pop edx
mov eax, 10
add eax, edx
ret
我将两者编译链接如下:
gcc -c prog.c -o prog_c.o -m32
nasm -f elf32 prog.asm -o prog_asm.o
gcc prog_c.o prog_asm.o -m32
但是,当我运行生成的文件时,我遇到了分段错误。
但是当我替换时
流行音乐
与
mov edx, [esp+4]
程序运行良好。有人能解释一下为什么会这样吗?
【问题讨论】:
-
pop edx移动堆栈指针,mov edx, [esp+4]不移动。通常在 C 中,由调用者来清理堆栈。 -
问得好问题。 +1
-
@Jabberwocky 但是为什么会导致分段错误呢?堆栈对于这两个函数是通用的,对吧?
-
因为你弹出了返回地址而不是参数。你不能像这样使用pop。
-
@SusmitAgrawal 因为返回地址在堆栈上。你的
pop edx实际上是从堆栈中弹出返回地址,当ret被执行时,处理器会跳转到堆栈上的任何地址