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?
That is insecure because str might contain format specifiers like %d , causing printf to attempt to read additional arguments that are not provided, thereby causing undefined behavior (probably printing other data on the stack).
In your first case, it takes 3 arguments. In the second case, it takes 4 arguments. printf is a variadic function. It takes a variable number of arguments.
Format specifiers define the type of data to be printed on standard output. You need to use format specifiers whether you're printing formatted output with printf() or accepting input with scanf() .
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With