I mistakenly wrote this code:
#include <stdio.h>
int main() {
printf("%d"); // Missing argument!
return 0;
}
Surprisingly, it compiled (warnings existed), but when I ran it, I got unexpected output or sometimes even a crash
printf("%d")
compile successfully despite the missing argument?printf("%d")
is executed without a corresponding integer?printf
is a variadic function
printf
takes a format string to interpret additional arguments. Since %d
expects an integer, but none is provided, printf
still tries to fetch an argument from the stack (or a register), leading to undefined behavior (UB).
Why does it compile?
C does not check the number of arguments passed to printf()
at compile time (unless warnings are enabled).
What happens at runtime?
Since printf("%d")
expects an integer but gets random data instead, the output is garbage or might cause a segmentation fault.
Always provide the correct argument:
printf("%d", 42); // Correct
Enable compiler warnings to catch such mistakes:
gcc -Wall -Wformat -o program program.c