[Bug tree-optimization/89706] -Wstringop-truncation strncpy message is confusing and has psuedo-false-positives

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Mar 13 19:55:00 GMT 2019


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

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |diagnostic
             Status|UNCONFIRMED                 |NEW
   Last reconfirmed|                            |2019-03-13
                 CC|                            |msebor at gcc dot gnu.org
          Component|c++                         |tree-optimization
             Blocks|                            |88781
     Ever confirmed|0                           |1

--- Comment #1 from Martin Sebor <msebor at gcc dot gnu.org> ---
The checker looks for a 'buf[N] = '\0';' statement immediately after the call
to strncpy and when it finds one it suppresses the warning.  But the logic is
less than perfect and doesn't handle this case where it sees:

  buf.2_7 = buf;
  __builtin_strncpy (buf.2_7, "Progress", sz_6);
  buf.3_8 = buf;
  _9 = buf.3_8 + sz_6;
  *_9 = 0;

It doesn't see that the _9 on the last line is related to buf.2_7 (the first
argument to strncpy).

In general, the warning (clearly naively) assumes strncpy and strncat are used
in meaningful but possibly incorrect ways.  Especially in "unusual" calls to
the functions like in the test case in comment #0 (but in some others as well)
the suppression logic may be ineffective and lead to false positives.  I'm
working on improving this but I doubt the improvements will make it into the
first release of GCC 9.

In the meantime, the false positive in this case can be suppressed by replacing
strncpy with stpncpy like so:

  inline void func(const char* s) {
    size_t sz = strlen(s);
    if (sz > len - 1)
        sz = len - 1;
    *stpncpy(buf, s, sz) = '\0';
  }


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88781
[Bug 88781] [meta-bug] bogus/missing -Wstringop-truncation warnings


More information about the Gcc-bugs mailing list