Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are printf/sprintf compiler warnings a conceptual break?

I have noticed that a large number of C compilers issue warnings when the conversion specifiers in the format string of the printf/sprintf functions do not match the type or the count of the corresponding arguments.

That seems to me like a conceptual break since C doesn't have built-in functions according to the language specification.

All the compiler should know about printf/sprintf is their prototypes and not their semantics. I know that printf/sprintf are standard C functions, but yet they reside in a separate library, libc, and you have to include stdio.h to import their prototypes.

What many compilers do instead is analyze the format string which could as well be supplied at runtime.

Does the above make sense?

like image 917
Blagovest Buyukliev Avatar asked Dec 01 '22 04:12

Blagovest Buyukliev


1 Answers

"All the compiler should know about printf/sprintf is their prototypes and not their semantics".

That's the part that isn't true. As far as the standard is concerned, any part of a C implementation is "allowed" to know about any other part, and to issue diagnostics that may be helpful to the user. Compiler intrinsics aren't required by the standard, and neither is this particular diagnostic, but they certainly aren't forbidden.

Note that (as far as the standard is concerned) the standard library is special, it's not just any old linked library. If a particular implementation/compiler even provides a mechanism for the user to link against a different version of the standard library, the standard certainly doesn't require it to "work" when that alternative library has different semantics from what is laid out in the standard.

So in that sense, everything in the standard library is "bult-ins". It's part of the C language specification. Compilers are allowed to act on the assumption that it behaves as the standard requires.

Of course, if the format specifier isn't known until runtime, then the compiler can't do a static check of the varargs. But when it is known at compile time, the compiler can assume the behaviour of printf just as validly as it can assume the behaviour of memcpy, or of integer addition.

like image 128
Steve Jessop Avatar answered Dec 06 '22 19:12

Steve Jessop