Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use __attribute__((__format__ (__printf__,...) in Clang to avoid format string is not a string literal?

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.

like image 866
user1343318 Avatar asked Jan 10 '23 17:01

user1343318


1 Answers

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.

like image 53
T.C. Avatar answered Jan 17 '23 13:01

T.C.