c array - warning: format not a string literal

bigl picture bigl · Mar 14, 2012 · Viewed 85.2k times · Source

I'm attempting to learn C and already I've run into an issue. I assume its trivial but I need to know it. I have written:

#include <stdio.h>
#include <string.h>

int main() 
{
    char str_a[20];

    strcpy(str_a, "Hello, world!\n");
    printf(str_a);
}

Once I attempt to compile it with: gcc -g -o char_array2 char_array2.c I receive an error saying:

char_array2.c: In function ‘main’:
char_array2.c:9:2: warning: format not a string literal and no format arguments [-Wformat-security]

Can anyone help please?

Answer

MByD picture MByD · Mar 14, 2012

When using printf, the format string is better be a string literal and not a variable:

printf("%s", str_a);