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?
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"
puts
will be presumably faster. — Jul 08, 2015 at 11:44 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 puts
is faster" is false, it's still false. — Jul 08, 2015 at 16:15 gcc
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