8.1 Warning for format string

The possible security vulnerability of uncontrolled format string22 in printf() and the similar functions can be detected and warned with GCC using the option -Wformat -Wformat-security.

Example of insecure code: format.c

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

int main(int argc, char** argv)
{
  if (argc == 2)
    {
      fprintf(stderr, argv[1]);
      fprintf(stderr, "\n");
    }
  else
    {
      fprintf(stderr,"Usage: %s ARG\n", argv[0]);
      exit(1);
    }
  return 0;
}

The insecure program format.c can be compiled without obvious warnings.

$ gcc -Wall format.c

The insecure program format.c can be compiled with the option -Wformat -Wformat-security with warnings.

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

The output shows that the format.c program compiled with the option -Wformat-security warns about the possible security vulnerability of uncontrolled format string.


Footnotes

(22)

http://en.wikipedia.org/wiki/Uncontrolled_format_string