Sonny Ordell
Sonny Ordell

Reputation: 334

Why does omitting an argument to printf print garbage?

I am using printf via assembly code. I note that in the following example if I ommit the expected argument, garbage is printed.

    .386
    .model flat, c
    .stack 100h
printf PROTO arg1:Ptr Byte, printlist:VARARG
    .data
msg3fmt byte 0Ah,"%s",0Ah,"test output",0Ah,0
    .code
main proc
    INVOKE printf, ADDR msg3fmt
    ret
main endp
    end

My question is why? Is there a set memory address printf uses expecting to find an argument? Why is anything printed at all since no argument is passed?

Upvotes: 1

Views: 339

Answers (2)

Sakuramochi
Sakuramochi

Reputation: 76

The reason is that the format specifiers tell printf how many arguments it should have received. Printf gets its data from the stack; if you don't provide any data for it then it will pull whatever happened to be on the stack and treat as an argument.

Upvotes: 6

Prasoon Saurav
Prasoon Saurav

Reputation: 92864

The Standard says

If the number of format specifiers in printf() is greater than the number of arguments the behavior is undefined.

Undefined Behavior means anything can happen.

Upvotes: 3

Related Questions