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

            Bug ID: 119148
           Summary: Inconsistent -Wstringop-truncation warning when using
                    strncpy
           Product: gcc
           Version: 15.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: paul.f.fee at gmail dot com
  Target Milestone: ---

I'm seeing an unexpected warning with GCC relating to strncpy().  First some
minimal code to illustrate the issue:

     1  #include <string.h>
     2  #include <assert.h>
     3
     4  int main()
     5  {
     6      const char *src = "123456";
     7      char arr[6] = {1,2,3,4,5,6};
     8      size_t l = 5;
     9      [[maybe_unused]] char *ptr = arr;
    10
    11  #define dst arr
    12  // #define dst ptr
    13
    14      strncpy(dst, src, l);
    15      dst[l] = '\0';
    16      assert(strlen(dst) == l);
    17  }

Compiled with: cc truncation.c -Wall -O1 && ./a.out

When the destination is an array, lines 14 and 15 in combination are safe,
there's no warning.  However, when we swap macros on lines 11 and 12, we get a
warning, though the assert still passes.

truncation.c:14:5: warning: ‘strncpy’ output truncated copying 5 bytes from a
string of length 6 [-Wstringop-truncation]

Why do we get a warning when the destination is a pointer rather than an array?

Reply via email to