Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling printf with excess arguments undefined behaviour?

Tags:

I wonder if this yields in undefined behaviour:

printf("Test %d %s", 123, "abc", "def", "ghi");

The first two arguments after the format string match the format string, so these are OK; but the 3rd and 4th arguments are in excess because there are no more corresponding format specifiers.

IMHO printf() should simply ignore these excess arguments and there should be no UB. Is this correct?

like image 773
Jabberwocky Avatar asked Jul 22 '15 09:07

Jabberwocky


People also ask

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

Is printf undefined behavior?

So, printf is producing undefined behavior because you are passing it an incompatible type of argument.

How many arguments can printf take?

Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) )


2 Answers

Yes, this scenario is explicitly defined by the standard. It is not undefined behaviour.

To quote the C11 standard, chapter §7.21.6.1, The fprintf() function

[...] If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored [...]

like image 61
Sourav Ghosh Avatar answered Sep 25 '22 08:09

Sourav Ghosh


Basically, printf (or any formatting function) will look into only 'n' number of %d, %c, %f..., etc in the format string from the variable list argument. Others are simply ignored.

like image 29
vivekn Avatar answered Sep 23 '22 08:09

vivekn