Why is printf with a single argument (without conversion specifiers) deprecated?
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
.
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"