简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM