【发布时间】:2016-02-06 16:39:25
【问题描述】:
我制作了一个程序,它接受一个字符串作为用户的输入,然后计算它的长度并显示它。但是当我运行程序时,我收到一个错误Segmentation fault (core dumped)。我的代码如下所示
str_len: ;Procedure to calculate length of String
xor rdx,rdx
xor rcx,rcx ;I want to store length in rcx
mov rdx,[string] ;string contains the input taken from the user
mov rsi,rdx
mov rcx,'0' ;By default rcx will contain '0' decimal
up: cmp byte[rsi],0 ;Compare if end of string
je str_o ;If yes then jump to str_o
inc rcx ;Increment rcx i.e., length
inc rsi ;Point to next location of rdx i.e.,string
jmp up ;Repeat till end of string
str_o: mov rax,1 ;Print final length
mov rdi,1
mov rsi,rcx
mov rdx,1
syscall
ret
我可以保证我的程序的其余部分是正确的。错误将出现在代码的上述部分。可能是什么错误?
【问题讨论】:
-
sys_write 系统调用写入字符串,而不是数字(或寄存器中的单个字符)。您需要将您的数字转换为字符串并将缓冲区地址(包含转换后的数字)传递给 sys_write。在您的情况下,您必须将
rcx中的值移动到临时缓冲区,然后将该缓冲区的地址传递给 sys_write。 -
谢谢,我会试试的
-
我试过你说的但还是一样的错误
-
另一个问题是字符串的地址加载不正确。
mov rdx,[string]正在移动从标签字符串开始的 8 个字节并将它们移动到 reigster 中。你想要string的地址。 -
我可以保证我的程序的其余部分是正确的。如果我们每次听到这个消息都能得到一美元,我们都会变得富有:)