cprintfundefined-behaviorcompiler-warningsformat-string

If there are insufficient arguments for the format, the behavior is undefined


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


Solution

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

    2. Why does it compile?

      C does not check the number of arguments passed to printf() at compile time (unless warnings are enabled).

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

    How to Fix it

    Always provide the correct argument:

    printf("%d", 42);  // Correct
    

    Enable compiler warnings to catch such mistakes:

    gcc -Wall -Wformat -o program program.c