The MASM Forum

General => The Campus => Topic started by: g6g6 on June 24, 2014, 06:08:36 AM

Title: Printf and Scanf in assembly
Post by: g6g6 on June 24, 2014, 06:08:36 AM
Hello, This is my code:

.386
.model flat,stdcall

option casemap:none
include \masm32\include\windows.inc
include \masm32\include\masm32.inc
include \masm32\include\msvcrt.inc
include \masm32\include\kernel32.inc

includelib \masm32\lib\masm32.lib
includelib \masm32\lib\msvcrt.lib
includelib \masm32\lib\kernel32.lib
.data

menss db "digita um numero:", 0
saida db "%d",0
saida2 db "x = %d",0

.data?

salvar dd ?

.code
start:
push offset menss
call crt_printf
push offset salvar ;push salvar
push offset saida
call crt_scanf
mov eax,offset salvar
push eax
push offset saida2
call crt_printf
; invoke crt_printf,addr saida2,salvar
push 0
call ExitProcess

end start

I want to digit a number, and my program will print this number.. But when I compile and run it:

C:\masm32\bin>ddd
digita um numero:3
x = 4206620

What is wrong?
Title: Re: Printf and Scanf in assembly
Post by: Vortex on June 24, 2014, 06:20:17 AM
printf is a C function. If you don't use invoke to call the this function, you need to balance the stack manually.
Title: Re: Printf and Scanf in assembly
Post by: g6g6 on June 24, 2014, 06:29:10 AM
Tks vortex.But, when I use this code:
     invoke crt_printf,addr menss
     invoke crt_scanf, addr saida, addr salvar
     invoke crt_printf,addr saida2,addr salvar

The result is the same, just works when I use this: invoke crt_printf,addr menss
     invoke crt_scanf, addr saida, addr salvar
     invoke crt_printf,addr saida2,salvar

Why?
Title: Re: Printf and Scanf in assembly
Post by: qWord on June 24, 2014, 06:33:55 AM
For printf integral types are passed by value. Also remarks that "%d" correspond to a DWORD sized integer value.
Title: Re: Printf and Scanf in assembly
Post by: g6g6 on June 24, 2014, 06:45:09 AM
Sorry, I continue not understanding... I should put " addr salvar". Because the integer is located in the addr of salvar.
Title: Re: Printf and Scanf in assembly
Post by: qWord on June 24, 2014, 06:54:03 AM
Pass by value means to push the actual value on the stack rather than a pointer:
push salvar
push offset saida2
call crt_printf
add esp,2*8
Title: Re: Printf and Scanf in assembly
Post by: g6g6 on June 24, 2014, 09:07:51 AM
But "push salvar" makes error
Title: Re: Printf and Scanf in assembly
Post by: dedndave on June 24, 2014, 09:14:29 AM
it should work
try....
    push dword ptr salvar
Title: Re: Printf and Scanf in assembly
Post by: g6g6 on June 24, 2014, 09:25:43 AM
Works, but what is ptr? I tried search, but I did not find meaning
Title: Re: Printf and Scanf in assembly
Post by: dedndave on June 24, 2014, 11:27:27 AM
PTR may be used in several ways (pointer)
however, in this case, it is a "size override" or "size specifier"
it simply tells the assembler what size the item is to PUSH