【问题标题】:scanf do not work fine with qword in assemblyscanf 在汇编中不能与 qword 一起正常工作
【发布时间】:2020-07-15 04:21:13
【问题描述】:

我在 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 中将 qword 更改为 dword 也是如此),则程序可以正常工作!

下面是汇编、链接和执行的命令:

nasm test.asm -f elf64
gcc test.o -no-pie
./a.out

【问题讨论】:

  • 请注意,32 位双字是用dd 声明的,而不是dw,后者用于16 位字。
  • 你是对的,dd 是正确的方法。感谢您的澄清。

标签: assembly scanf 64-bit x86-64 nasm


【解决方案1】:

您正在使用 %d 调用 scanf,它对应于指向 int 的指针。 int 通常是 32 位(dword)而不是 64 位(qword)。将 numFormat 更改为 '%ld',就可以正常工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2014-07-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多