Search code examples
assemblyprintfscanfmasmmasm32

printf error printing a char in masm32


This is the first time that i write here... I try to explain my problem! I wrote this code in masm32

.586
.model flat
.data

mess db "digita un carattere    ",0
res db "x = %c",10,0

.data?
salva db ?

.code
extern _printf:proc
extern _scanf:proc

_funzione proc
;pre
push ebp
mov ebp,esp
push ebx
push edi
push esi

mov eax, offset mess
push eax
call _printf ;puting out the message
mov eax, offset salva
push eax
mov eax, offset res
push eax
call _scanf ;taking the char and saving it in "salva"
add esp,12
xor eax,eax
mov eax,offset salva
push eax
mov eax, offset res
push eax
call _printf ;printing the char
add esp,8

;post
pop esi
pop edi
pop ebx
pop ebp

ret
_funzione endp
end

When i compile it the output is:

output

I dont understand why _printf doesnt print the char ('y') that _scanf had read... Please help me!


Solution

  • The format strings of printf and scanfare very different. The scanf format string controls only the input, scanf does not output something (just echo the inputted character). scanf will produce nothing but an error with res db "x = %c",10,0. Add a line scanf_res db "%c",0 and change mov eax, offset res to mov eax, offset scanf_res.

    The printf format string res db "x = %c",10,0 expects a direct value to be pushed, not an offset of a string. Change mov eax,offset salva to mov al, salva.

    .586
    .model flat
    .data
    
    mess db "digita un carattere    ",0
    scanf_res db "%c",0
    res db "x = %c",10,0
    
    .data?
    salva db ?
    
    .code
    extern _printf:proc
    extern _scanf:proc
    extern _fflush:proc
    
    _funzione proc
    ;pre
    push ebp
    mov ebp,esp
    push ebx
    push edi
    push esi
    
    mov eax, offset mess
    push eax
    call _printf ;puting out the message
    mov eax, offset salva
    push eax
    mov eax, offset scanf_res
    push eax
    call _scanf ;taking the char and saving it in "salva"
    add esp,12
    
    xor eax,eax
    mov al, salva
    push eax
    mov eax, offset res
    push eax
    call _printf ;printing the char
    add esp,8
    
    ;post
    pop esi
    pop edi
    pop ebx
    pop ebp
    
    ret
    _funzione endp
    end