我在Ubuntu中制作了一个小的64位NASM汇编程序来测试scanf C函数,但如果目标字段是qword,则无法正常工作。
global main
extern printf
extern scanf
section .data
msgInNum db 'Type a number: ',0
numFormat db '%d',0
msgOuNum db 'Your input %d ',10,0
number dq 0
section .bss
section .text
main:
push rbp
other:
mov rdi,msgInNum
xor rax,rax
call printf
mov rdi,numFormat
mov rsi,number
mov al,0
call scanf
mov rdi,msgOuNum
mov rsi,[number]
xor rax,rax
call printf
cmp qword[number],0
jge other
pop rbp
ret
问题是程序永远不会结束,因为当我键入时,cmp指令永远不会在数字中找到负值,例如scanf的-1。但问题是,如果我把数字的定义改为dw而不是dq(在cmp中也一样,用dword改qword(,程序就可以正常工作了!
以下是组装、链接和执行的命令:
nasm test.asm -f elf64
gcc test.o -no-pie
./a.out
您用%d调用scanf,它对应于指向int的指针。int通常是32位(dword(而不是64位(qword(。将numFormat更改为"%ld",它将按预期工作。