Programming
c security printf format-specifiers puts
Updated Sat, 25 Jun 2022 13:37:30 GMT

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


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?




Solution

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"




Comments (5)

  • +0 – Further to causing the program to crash, there are many other exploits possible with format strings. See here for more info: en.wikipedia.org/wiki/Uncontrolled_format_string — Jul 08, 2015 at 11:19  
  • +9 – Another reason is that puts will be presumably faster. — Jul 08, 2015 at 11:44  
  • +0 – @black: puts is "presumably" faster, and this is probably another reason people recommend it, but it is not actually faster. I just printed "Hello, world!" 1,000,000 times, both ways. With printf it took 0.92 seconds. With puts it took 0.93 seconds. There are things to worry about when it comes to efficiency, but printf vs. puts is not one of them. — Jul 08, 2015 at 14:21  
  • +0 – @KonstantinWeitz: But (a) I was not using gcc, and (b) it doesn't matter why the claim "puts is faster" is false, it's still false. — Jul 08, 2015 at 16:15  
  • +8gcc automatically converts printf to puts when there is only a single argument, the format string doesn't contain any %-field, and it's terminated with '\n'. No need to activate optimizations for that. Just look at the assembly code produced by gcc -S. — Jul 14, 2015 at 19:09