bug-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

bug#32189: 27.0.50; GCC 7 warning due to -Wformat-truncation=2


From: Ken Brown
Subject: bug#32189: 27.0.50; GCC 7 warning due to -Wformat-truncation=2
Date: Wed, 18 Jul 2018 15:42:55 -0400
User-agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.9.1

On 7/18/2018 11:09 AM, Eli Zaretskii wrote:
From: Ken Brown <address@hidden>
Date: Tue, 17 Jul 2018 15:26:34 -0400

I'm getting the following warning when building the master branch on
Cygwin with GCC 7.3:

In file included from /usr/include/stdio.h:800:0,
                   from ../lib/stdio.h:43,
                   from ../../master/src/w32cygwinx.c:22:
../../master/src/w32cygwinx.c: In function ‘Fw32_battery_status’:
../../master/src/w32cygwinx.c:116:26: warning: ‘%3.1f’ directive output
may be truncated writing between 3 and 312 bytes into a region of size
16 [-Wformat-truncation=]
      snprintf (buffer, 16, "%3.1f", h);
                            ^
../../master/src/w32cygwinx.c:116:4: note: ‘__builtin_snprintf’ output
between 4 and 313 bytes into a destination of size 16
      snprintf (buffer, 16, "%3.1f", h);
      ^

Do we really need to use -Wformat-truncation?  Is it a useful warning
switch?  The above sounds like useless noise, because the code
explicitly _asks_ for truncation.  What do people think about this?

Moreover, the warning isn't very smart; see below.

The attached patch avoids the warning.  Is this a reasonable fix, or is
there a better way?

I think if we keep the switch, a better fix is to do this:

      snprintf (buffer, 16, "%ld", h % 1000000);

      m = seconds_left / 60;
      snprintf (buffer, 16, "%ld", m % 20000);

etc., you get the point.

This doesn't work with GCC 7. (Maybe it would work with GCC 8; the release notes say that it is better at avoiding false positives.) For integer specifiers like "%ld", the only thing I've found that works without enlarging the buffer is to cast the argument to a smaller integer type. For float specifiers like "%3.1f", even using a small type doesn't seem to work. For example:

$ cat test.c
#include <stdio.h>
int
main ()
{
  char buffer[16];
  short a;
  snprintf (buffer, 16, "%3.1f", a);
}

$ gcc -Wformat-truncation=2 test.c
test.c: In function ‘main’:
test.c:8:26: warning: ‘%3.1f’ directive output may be truncated writing between 3 and 312 bytes into a region of size 16 [-Wformat-truncation=]
   snprintf (buffer, 16, "%3.1f", a);
                          ^~~~~
test.c:8:3: note: ‘snprintf’ output between 4 and 313 bytes into a destination of size 16
   snprintf (buffer, 16, "%3.1f", a);
   ^~~~~~~~~~~~~~~~~~~~~

Ken





reply via email to

[Prev in Thread] Current Thread [Next in Thread]