It is suggested here and here that to avoid warning 'format string is not a string literal' in Clang, one should use the following __attribute__
code section before the function definition to tell Clang that one of the functions from printf
family is being called inside the function:
__attribute__((__format__ (__printf__, 3, 0)))
My question is why? I have looked at official documentation here but can not really pon-point the issue.
The point is that it's generally a pretty bad idea to pass arbitrary input as printf
format strings. One type mismatch and you got a one-way ticket to Undefined Behavior land (not to mention the dreaded %n
specifier that can cause writing to arbitrary memory with a mismatch).
For that reason, GCC and clang will complain if you call printf
with a non-literal (and if you call it with a literal format string, they will check the format string against the provided arguments). The __attribute__((__format__ (__printf__,...)
tells the compiler that one of your parameters is a printf
format string and causes the checking to be applied when that function is called. Since the compiler knows that the format string parameter will be checked when your function is called, it won't complain about you using that parameter as a format string inside your function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With