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

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


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"


printf("Hello world");

is fine and has no security vulnerability.

The problem lies with:

printf(p);

where p is a pointer to an input that is controlled by the user. It is prone to format strings attacks: user can insert conversion specifications to take control of the program, e.g., %x to dump memory or %n to overwrite memory.

Note that puts("Hello world") is not equivalent in behavior to printf("Hello world") but to printf("Hello world\n"). Compilers usually are smart enough to optimize the latter call to replace it with puts.


Further to the other answers, printf("Hello world! I am 50% happy today") is an easy bug to make, potentially causing all manner of nasty memory problems (it's UB!).

It's just simpler, easier and more robust to "require" programmers to be absolutely clear when they want a verbatim string and nothing else.

And that's what printf("%s", "Hello world! I am 50% happy today") gets you. It's entirely foolproof.

(Steve, of course printf("He has %d cherries\n", ncherries) is absolutely not the same thing; in this case, the programmer is not in "verbatim string" mindset; she is in "format string" mindset.)