On 07/01/2016 08:15 PM, Martin Sebor wrote:
The attached patch enhances compile-time checking for buffer overflow
and output truncation in non-trivial calls to the sprintf family of
functions under a new option -Wformat-length=[12].  This initial
patch handles printf directives with string, integer, and simple
floating arguments but eventually I'd like to extend it all other
functions and directives for which it makes sense.

I tried your patch with the following code, which is close to a real-world example:

#include <stdio.h>

void print (const char *);

void
format_1 (unsigned address)
{
  unsigned char a = address >> 24;
  unsigned char b = address >> 16;
  unsigned char c = address >> 8;
  unsigned char d = address;
  char buf[15];
  sprintf ("%u.%u.%u.%u", buf, a, b, c, d);
  print (buf);
}

void
format_2 (unsigned address)
{
  char buf[15];
  sprintf ("%u.%u.%u.%u", buf,
           address >> 24,
           (address >> 16) & 0xff,
           (address >> 8) & 0xff,
           address & 0xff);
  print (buf);
}

I didn't get a warning (with -O2 and -Wformat-length=1 or -Wformat-length=2). If the warning is implemented in builtin folding, I guess this has to be expected because there is no range information, and warning for all %us similar to those in the example would produce too many false positives.

Florian

Reply via email to