jean
jean

Reputation: 1013

Scanf on nasm assembly program

I am trying to write a simple program using scanf and printf, but it is not storing my values properly.

        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

For some reason when I run the program, no matter what number I enter, the program prints 1 for both inputs.

I am using nasm, linked with gcc

Upvotes: 0

Views: 1651

Answers (1)

Michael
Michael

Reputation: 58467

You're making an incorrect assumption here:

call scanf
mov ebx, eax            ;ebx holds input

scanf actually returns "the number of items of the argument list successfully filled" (source). Your integer is in location.
By the way, you should probably make location at least 4 bytes (i.e. use dd instead of dw).

Upvotes: 3

Related Questions