Search code examples
assemblyiox86user-inputfgets

receiving input using fgets in assembly


I got a problem with reading to a buffer using fgets in assemmbly. I know that the numbers are equal to the ASCII value ATM , and its not the problem. I cant get the real value of the user input. Before using fgets I am required to print the string: "calc:" and i think its messing with my real input.

section .rodata

        CALC:   DB "calc:" , 10 , 0         ;format string 

section .bss
        buffer:         resb 80             ;store my input

;....more data, not relevant

push CALC                       ;push string to stuck
call printf             
add esp, 4                      ;remove pushed argument

push dword [stdin]              ;fgets need 3 param
push dword 80                   ;max lenght
push dword buffer               ;input buffer
call fgets
add esp, 12                     ;remove 3 push from stuck

mov ecx, [buffer]              ;THIS IS FOR GDB
stop_here:

Now, the problem is that the value in buffer isn't what the user put in the input. when I used the GDB debugger for better understanding I got the following results:

input 0  --> ecx value is: 2608  (should be 48)
input 1  --> ecx value is: 2609  (should be 49)
input 10 --> ecx value is: 667697 (should be 48+49)
input 34 --> ecx value is: 668723 (should be 51+52)

EDIT: I tryed using gets instead, and now it works! can someone PLEASE explain to me why?!

EDIT- 5 years later - I can't believe I knew this much assembly back then


Solution

  • fgets stores the terminating line feed into the buffer as well, and since you are loading 4 bytes into ecx, you will also see that.

    2608 = 0A30 hex = '0' LF
    667697 = 0A3031 hex = '1' '0' LF
    

    (Remember that x86 is little endian.)