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

--- Comment #4 from Martin Sebor <msebor at gcc dot gnu.org> ---
Using strncpy or strlen to cross subobject boundaries isn't valid.  GCC catches
the strncpy bug with -Warray-bounds:

pr86265.c: In function ‘main’:
...
In file included from /usr/include/string.h:630,
                 from pr86265.c:2:
pr86265.c:13:3: warning: ‘__builtin_strncpy’ offset [5, 104] from the object at
‘s’ is out of the bounds of referenced subobject ‘data’ with type ‘char[4]’ at
offset 0 [-Warray-bounds]
   strncpy(s.data, argv[1], 4 + 100);
   ^~~~~~~

Use memcpy (&s, ...) and memchr (&s, ...) to get that effect.  To make it
strictly valid, be sure to pass to the functions the address of the enclosing
object rather than a pointer to one of its members:

  struct S s = { "", "" };
  memcpy (&s, argv[1], strlen (argv[1]));
  int length = min((char*)memchr (&s, 0, sizeof s) - (char*)&s, 4);

(-Warray-bounds lets raw memory functions like memcpy and memchr cross
subobject boundaries without being diagnosed.)

Reply via email to