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

            Bug ID: 89706
           Summary: -Wstringop-truncation strncpy message is confusing and
                    has psuedo-false-positives
           Product: gcc
           Version: 9.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redbeard0531 at gmail dot com
  Target Milestone: ---

https://godbolt.org/z/BAeXQB

"strncpy output truncated copying between 0 and 8 bytes from a string of length
8" doesn't make it obvious what the problem with the is or how to solve it.
Once I decoded it[1], I realized it was warning about something the code was
already set up to handle correctly. Specifically, the last line of func
re-establishes the nul byte termination regardless of how many bytes are
copied. (Yes I know that this code is a dumb use of strncpy and we should
probably just be using memcpy, but that isn't what this warning is warning
about.)


[1] I was only able to decode it by tweaking the code until I got the "output
truncated before terminating nul copying 8 bytes from a string of the same
length" form of the warning. This happens if you comment out the if-block in
this code.


#include <cstring>

extern size_t len;
extern char *buf;

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

void test() {
    const char* p = "Progress";
    func(p);
}

> g++ -Wstringop-truncation -O2

In function 'void func(const char*)',
    inlined from 'void test()' at <source>:16:9:
<source>:10:12: warning: 'char* strncpy(char*, const char*, size_t)' output
truncated copying between 0 and 8 bytes from a string of length 8
[-Wstringop-truncation]
   10 |     strncpy(buf, s, sz);
      |     ~~~~~~~^~~~~~~~~~~~

Reply via email to