【发布时间】:2016-05-04 13:46:10
【问题描述】:
我想在汇编程序中创建一个从 c 调用的函数,它将一个字节(char)写入文件。下面是函数在 c 中的样子:
void writebyte (FILE *f, char b)
{
fwrite(&b, 1, 1, f);
}
下面是调用它的代码:
#include <stdio.h>
extern void writebyte(FILE *, char);
int main(void) {
FILE *f = fopen("test.txt", "w");
writebyte(f, 1);
fclose(f);
return 0;
}
到目前为止,我想出了以下汇编代码:
.global writebyte
writebyte:
pushl %ebp
movl %esp, %ebp #standard params
pushl 12(%ebp) # pushing byte to the stack
pushl $1
pushl $1
pushl 8(%ebp) #file to write
call fwrite
popl %ebp
ret
我不断从 gdb 获取信息:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0xffa9702c in ?? ()
如何在汇编中编写这样的函数?
编辑:我使用的是 Ubuntu 16.04
【问题讨论】:
-
由于您没有带汇编程序的 std 库,因此代码将依赖于操作系统。
-
我使用的是 ubuntu 16.04
-
调用fwrite的第一个参数是指向字节的地址,而不是字节本身;假设您已正确链接程序,您很可能会遇到 seg 错误,因为 fwrite 试图将您的字节用作地址,并访问未映射到虚拟地址空间中的地址的内存。
-
你也不清理堆栈。