Why is printf with a single argument (without conversion specifiers) deprecated?

StackUser picture StackUser · Jul 8, 2015 · Viewed 14.3k times · Source

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!");

with

puts("Hello World!");

or

printf("%s", "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?

Answer

Jabberwocky picture Jabberwocky · Jul 8, 2015

printf("Hello World!"); is IMHO not vulnerable but consider this:

const char *str;
...
printf(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.

Example:

printf("%s");   //undefined behaviour (mostly crash)
puts("%s");     // displays "%s\n"