【问题标题】:Scanf on nasm assembly programnasm 汇编程序上的 Scanf
【发布时间】:2014-11-03 19:02:00
【问题描述】:

我正在尝试使用scanfprintf 编写一个简单的程序,但它没有正确存储我的值。

        extern printf
        extern scanf

        SECTION .data
  str1: db "Enter a number: ",0,10
  str2: db "your value is %d, squared = %d",0,10
  fmt1: db "%d",0
  location: dw 0h


        SECTION .bss
  input1: resw 1 

        SECTION .text
        global main

   main:
        push ebp
        mov ebp, esp

        push str1
        call printf 
        add esp, 4

        push location
        push fmt1 
        call scanf
        mov ebx, eax            ;ebx holds input

        mul eax                 ;eax holds input*input

        push eax
        push ebx
        push dword str2
        call printf
        add esp, 12

        mov esp, ebp
        pop ebp
        mov eax,0
        ret

由于某种原因,当我运行程序时,无论我输入什么数字,程序都会为两个输入打印 1。

我正在使用 nasm,与 gcc 链接

【问题讨论】:

    标签: gcc assembly nasm


    【解决方案1】:

    您在这里做出了错误的假设:

    call scanf
    mov ebx, eax            ;ebx holds input
    

    scanf实际上返回“成功填充的参数列表的项目数”source)。您的整数在 location.
    顺便说一句,您可能应该使 location 至少 4 个字节(即使用 dd 而不是 dw)。

    【讨论】:

    • 此外,调用约定要求应保留ebx。您可能想改用ecx。此外,在call scanf 之后缺少一个add esp, 8,但在这种情况下这是无害的,因为您从ebp 恢复了堆栈指针。
    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 2013-02-06
    • 2014-12-26
    • 2018-09-08
    • 2017-12-26
    • 2014-01-03
    • 1970-01-01
    • 2011-10-14
    相关资源
    最近更新 更多