为什么不推荐使用带有单个参数(没有转换说明符)的 printf ? [英] Why is printf with a single argument (without conversion specifiers) deprecated?
问题描述
在我正在阅读的一本书中,写到带有单个参数(没有转换说明符)的 printf
已被弃用.建议替换
In a book that I'm reading, it's written that printf
with a single argument (without conversion specifiers) is deprecated. It recommends to substitute
printf("Hello World!");
与
puts("Hello World!");
或
printf("%s", "Hello World!");
谁能告诉我为什么 printf("Hello World!");
是错误的?书中写道,它包含漏洞.这些漏洞是什么?
Can someone tell me why printf("Hello World!");
is wrong? It is written in the book that it contains vulnerabilities. What are these vulnerabilities?
推荐答案
printf("Hello World!");
恕我直言不容易受到攻击,但请考虑:
printf("Hello World!");
is IMHO not vulnerable but consider this:
const char *str;
...
printf(str);
如果 str
碰巧指向一个包含 %s
格式说明符的字符串,你的程序将表现出未定义的行为(主要是崩溃),而 puts(str)
将按原样显示字符串.
If str
happens to point to a string containing %s
format specifiers, your program will exhibit undefined behaviour (mostly a crash), whereas puts(str)
will just display the string as is.
示例:
printf("%s"); //undefined behaviour (mostly crash)
puts("%s"); // displays "%s
"
这篇关于为什么不推荐使用带有单个参数(没有转换说明符)的 printf ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!