#include<stdio.h>
int main()
{
const char arr[10] = "hello";
printf(arr);
return 0;
}
When compiling the above code with don't gave any warning. But when I remove the
const from const char arr[10] it gives a warning:
<source>: In function 'main':
<source>:5:10: warning: format not a string literal and no format arguments [-Wformat-security]
5 | printf(arr);
|
Why I am getting like this? How the const keyword make difference? Here I am compiling with gcc -Wformat -Wformat-security ….
printf()requires you to provide a format string, and allows you to provide additional arguments as needed to match whatever conversion specifiers appear in the format.It is risky, in general, to use a modifiable string as a
printfformat, because it may turn out to have unexpected conversion specifiers in it. This is primarily an issue with data read at runtime, and your particular string would be ok, but GCC's warning doesn't look so deeply. It just sees a modifiable string as a format and issues the warning.Safer alternatives that will not draw a warning from gcc would include using
fputs():... and using
printf()with an appropriate format:.
Apparently GCC does not distinguish between an array of
const charand a string literal for this purpose. That's not unreasonable, but it does make the diagnostic a little confusing.