为什么不推荐使用带有单个参数(没有转换说明符)的 printf ?

为什么不推荐使用带有单个参数(没有转换说明符)的 printf ?

问题描述:

在我正在阅读的一本书中,写到带有单个参数(没有转换说明符)的 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
"