Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: format string is not a string literal

Tags:

c

string

gcc

I have written a simple program in C, which allocates memory for a string vector and then prints this.

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

int main() {
    char str_a[20];

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

Using compiler gcc, this gives a compilation error:

char_array2.c:8:12: warning: format string is not a string literal
      (potentially insecure) [-Wformat-security]
    printf(str_a);

1 warning generated.

I do not understand why I am getting a warning. Can someone explain it to me?

like image 417
ShanZhengYang Avatar asked Sep 02 '15 20:09

ShanZhengYang


1 Answers

Use:

printf("%s", str_a);

to get rid of the warning when -Wformat-security is enabled.

The diagnostic is informative to avoid format string vulnerability. For example:

strcpy(str_a, "%x%x%x%x");
printf(str_a);

would be equivalent to:

printf("%x%x%x%x");

which is missing the required arguments and can be used by an attacker to dump the stack (assuming str_a is under user control, which is not the case in your program, but gcc is not smart enough to figure).

like image 168
ouah Avatar answered Sep 24 '22 17:09

ouah