Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 829
StackUser Avatar asked Jul 08 '15 11:07

StackUser


People also ask

Why printf is insecure?

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).

How many arguments can printf take in C?

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.

Why are format specifiers important?

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() .

What is %B in printf?

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).


1 Answers

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" 
like image 177
Jabberwocky Avatar answered Sep 22 '22 02:09

Jabberwocky