Why does omitting an argument to printf print garbage?-Collection of common programming errors

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?

  1. 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.

  2. 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.

Originally posted 2013-11-09 23:13:10.