c array – warning: format not a string literal

c array – warning: format not a string literal

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

printf(%s, str_a);

Just to add something to other answers, you better do this because a (long?) time ago people wrote printf like that and hackers found a way to read from and write to the stack, more here.
For example, a simple program like this:

[email protected]:~$ cat format_vul.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
    char text[1024];
    static int test_var = -1;

    if(argc < 2) {
        printf(Use: %s <input>n, argv[0]);

    strcpy(text, argv[1]);

    printf(The correct way:n);
    printf(%s, text);

    printf(nThe wrong way:n);

    printf(n[*]: test_var @ %8p = %d ( 0x%x )n, &test_var, test_var, test_var);
[email protected]:~$ ./format_vul AAAA
The correct way:
The wrong way:
[*]: test_var @ 0x804a024 = -1 ( 0xffffffff )

Can be used to change test_vars value from 0xffffff to something else, like 0xaabbccdd:

[email protected]:~$ ./format_vul $(printf x24xa0x04x08JUNKx2
The correct way:
The wrong way:
$�JUNK%�JUNK&�JUNK�.bfffefec.  154d7c.  155d7c.  155d7c.      f0.      f0.b
ffff4a4.       4.       4.                                                  



[*]: test_var @ 0x804a024 = -1430532899 ( 0xaabbccdd )

c array – warning: format not a string literal

The warning is caused by the compiler wanting the first argument of printf to be a string literal. It wants you to write this:

printf(%sn, str_a);

This is because the first parameter of printf is the format string. The format arguments are then passed after that.

Note: You can in fact use a variable as a format string, but you probably shouldnt do that. Thats why the compiler issues a warning and not an error.

Leave a Reply

Your email address will not be published.