<分区>
所以我正在尝试实现 itoa,它将 int 转换为字符串。 到目前为止,如果我不在 .loop 部分中循环并坚持使用小数字,则该实现是有效的。一旦它循环,我的程序就会出现段错误。
代码如下:
section .data
buffer times 11 db 0
section .text
global ft_itoa
extern ft_strrevd
extern malloc
ft_itoa:
mov rcx, 1 ;initialize our counter at 1 for the terminating null byte
mov rax, rdi ;move number in RAX for DIV instruction
push rbx ;save RBX
mov bl, 10
.check_negative:
and edi, 0xf0000000
mov rdi, buffer
jz .loop ;number is positive, proceed to main loop
not rax ;else
inc rax ;compute absolute value with binary complement
mov r9, 1 ;set neg flag
.loop:
cmp rax, 0
jz .check_neg_flag
div bl
add ah, 48 ;convert int to char
mov byte[rdi + rcx - 1], ah ;copy char in buffer
sub ah, 48
inc rcx
jmp .loop ;commenting this line prevents crash
.check_neg_flag:
cmp r9, 1
jne .dup
mov byte[rdi + rcx - 1], '-'
inc rcx
.dup:
mov byte[rdi + rcx - 1], 0
call ft_strrevd ;copy buffer string in memory and return pointer
.end:
pop rbx ;restore RBX
ret
这很可能是由 div 引起的,但我无法理解它的工作原理。 如果有人能指出我的解决方案,我们将不胜感激。