Error: string formatting is not a string literal

I wrote a simple C program that allocates memory for a row 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 the 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 this to me?

+4
source share
5 answers

Using:

printf("%s", str_a);

to get rid of the warning when turned on -Wformat-security.

Diagnostics are informative to avoid format string vulnerabilities . For example:

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

will be equivalent to:

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

(, str_a , , gcc , ).

+11

3 printf(). , ?

void foo(const char *str_a,int x) {
  printf("Hello %d\n", x);  // Compiler sees this is good
  printf("Hello %d\n");     // Compiler sees this is bad --> warning/error
  printf(str_a, x);         // Compiler cannot tell - thus the warning
}
+5

, . printf - printf("%s", str_a). , (""), , , , . , , ; - .

+3

- :

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

int main() {
    char str_a[20];

    fgets(str_a, 20, stdin);
    printf(str_a);
}

, A %s bad %n string, , , .

:

printf("A %s bad %n string");

%s , %n .

0

, , %d, ( int), . , , , . -to-char .

Note that inconsistent format specifiers (or argument types) cause undefined behavior and often result in conversion or garbage value failures. Think about what happens when a %sis associated with an integral value.

0
source

Source: https://habr.com/ru/post/1605636/


All Articles