我是汇编新手,我试图一次打印字符串的一个字符,目前为止有这个。
.equ STDOUT,1
.equ WRITE,4
.equ EXIT,1
char_string:
.asciz "hello, world"
.text
.globl _start
_start:
movl $char_string, %eax
call print_str
movl $EXIT, %eax
int $0X80
print_str:
mov (%eax), %ebx
movl $WRITE, %eax
movl $STDOUT, %ebx
movl $char_string, %ecx
movl $1, %edx
int $0x80
inc %eax
cmpl $0, %ebx
jne print_str
je out_of_loop
out_of_loop:
ret
然而,当我尝试编译时,我在行中得到分段错误move (%eax), %ebx
这有什么问题?我该如何修复它?我试图将字符串的指向字符移动到%ebx用于打印,然后稍后我增加eax以移动到字符串中的下一个字符。
崩溃的直接原因是使用eax
作为系统调用的返回值。但是,您的代码在其他方面也是错误的。我已经注释了你的代码:
print_str:
mov (%eax), %ebx # loads 4 bytes not 1
movl $WRITE, %eax
movl $STDOUT, %ebx # overwrites ebx you loaded
movl $char_string, %ecx # uses the starting address instead of iterating
movl $1, %edx
int $0x80
inc %eax # eax is return value of system call by now
cmpl $0, %ebx # ebx is $STDOUT, see above
jne print_str
je out_of_loop # makes no sense to jump to next instruction
out_of_loop:
ret
一个可能的解决方案是:
print_str:
mov %eax, %ecx # address of char to print
movl $STDOUT, %ebx
movl $1, %edx
print_str_loop:
cmpb $0, (%ecx) # test for terminating zero byte
je out_of_loop
movl $WRITE, %eax # reload eax as it is return value from a previous iteration
int $0x80
inc %ecx # point to next character
jmp print_str_loop
out_of_loop:
ret