Does calling printf invoke undefined behavior without an appropriate prototype?

Does this innocent looking program do undefined behavior:

int main(void) { printf("%d\n", 1); return 0; } 
+6
source share
1 answer

Yes, calling printf() without a proper prototype (from the standard <stdio.h> header or from a correctly written declaration) causes undefined behavior.

As indicated in C11 Appendix J (for reference only)

J2 undefined Behavior

  • To call a function without a function prototype in the area where the function is determined by the function prototype, either the prototype ends with an ellipsis, or the types of arguments after promotion are not compatible with the types of parameters (6.5.2.2).

This application is not normative, but explicitly documents the code above as an example of undefined behavior.

In more pragmatic words, in the absence of a prototype for printf , the compiler generates the calling sequence as if printf were defined as int printf(const char*, int) , which could be completely different and incompatible with the actual implementation of printf in the standard library defined as int printf(const char restrict *format, ...) .

Ancient ABIs were regular enough to not cause a problem, but modern (for example, 64-bit) ABIs use more efficient call sequences that make the specified code definitely incorrect.

As a result, this famous classic C program will also fail without #include <stdio.h> or at least a suitable prototype for printf :

 int main(void) { printf("Hello world\n"); // undefined behavior return 0; } 
+10
source

All Articles