2014-11-03 47 views
0

我正在尝试使用scanfprintf来编写一个简单的程序,但它并未正确存储我的值。nasm汇编程序上的scanf

 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链接

回答

3

你做出不正确的假设,在这里:

call scanf 
mov ebx, eax   ;ebx holds input 

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

+2

此外,调用约定强制应该保留'ebx'。您可能想使用'ecx'来代替。此外,在调用scanf后还有一个'add esp,8',但在这种情况下这没有害处,因为你从'ebp'恢复堆栈指针。 – Jester 2014-11-03 19:18:49