Why does format string is not a string literal error occur?


According to the standard, the printf function has a prototype: int printf(const char *restrict format, ...);

Actually, subject:

#include <stdio.h>

int main (void)
    const char *format = "hello world!";

    return 0;

Protest Clang :

printf.c:7:12: error: format string is not a string literal
      (potentially insecure) [-Werror,-Wformat-security]
printf.c:7:12: note: treat the string as an argument to avoid this
1 error generated

Why does such an error occur? After all, the format string corresponds to the prototype.


Actually, clang swears at something completely different. The first mistake he says is that it would be nice to explicitly set the formatting string as a literal, not a variable, since someone can accidentally change or replace a variable. And explicit is always better. A similar format string has been the cause of bugs and vulnerabilities so many times that clang decides to warn.

In the second line, he says that it is more beautiful to write this construction like this

printf("%s", format);

But sometimes it's better to just write


But the error is actually caused by -Werror , which causes warning to be treated as errors.

Scroll to Top