https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97817

            Bug ID: 97817
           Summary: -Wformat-truncation=2 elicits invalid warning
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jim at meyering dot net
  Target Milestone: ---

Here's the invalid warning.
The buffer's size is obviously not 6. It is AT LEAST 6.

$ gcc -Wformat-truncation=2 -O2 -c strerror_r.c
strerror_r.c: In function ‘strerror_r’:
strerror_r.c:12:35: warning: ‘Unknown error ’ directive output truncated
writing 14 bytes into a region of size 6 [-Wformat-truncation=]
   12 |     snprintf (buf, buflen, "Unknown error %d", errnum);
      |                             ~~~~~~^~~~~~~~
strerror_r.c:12:5: note: ‘snprintf’ output between 16 and 26 bytes into a
destination of size 6
   12 |     snprintf (buf, buflen, "Unknown error %d", errnum);
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here's the reduced test case (from gnulib's strerror.c):

$ cat strerror_r.c
#define size_t unsigned long long
extern int snprintf (char *__restrict __s, size_t __maxlen,
                     const char *__restrict __format, ...)
  __attribute__ ((__format__ (__printf__, 3, 4)));
extern int __xpg_strerror_r (int errnum, char *buf, size_t buflen);
int strerror_r (int errnum, char *buf, size_t buflen)
{
  if (buflen <= 5)
    return 9;
  int ret = __xpg_strerror_r (errnum, buf, buflen);
  if (ret == 1 && !*buf)
    snprintf (buf, buflen, "Unknown error %d", errnum);
  return ret;
}

Reply via email to