简体   繁体   English

为什么省略对printf的参数会打印垃圾?

[英]Why does omitting an argument to printf print garbage?

I am using printf via assembly code. 我通过汇编代码使用printf。 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? 是否有一个设置内存地址,printf期望用于查找自变量? 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应该接收多少个参数。 Printf gets its data from the stack; Printf从堆栈中获取数据; 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. 如果printf()中格式说明符的数量大于参数的数量,则行为未定义。

Undefined Behavior means anything can happen. 未定义的行为意味着任何事情都可能发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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