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

            Bug ID: 81849
           Summary: missing -Wstringop-overflow writing to the last
                    element of a struct
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

GCC diagnoses buffer overflow when using string functions like strcpy and
strncpy to write to struct members other than the last one, but it fails to
detect the same buffer overflow when writing to an array that's the last member
of a struct even when the size of the array is known to be non-zero.  That's
apparently because some code abuses the last element array element as a
flexible array member.  This choice may be necessary to avoid runtime aborts
when using _FORTIFY_SOURCE but it is not necessary to avoid warnings.  Code
that does this should be changed to replace the array with a flexible array
member or with the zero-length array extension and the warning would help with
that transition.

If it's thought important to provide an escape hatch from the stricter warning
(I'm not convinced it is) it may be worth considering making an exception for
memcpy but warning on all other functions.

$ cat z.c && gcc -O2 -S -Wall -Wextra -Wpedantic -Wunused z.c
struct A
{
  char a[8];
  void (*pf)(void);
};

void f (struct A *a, const char *s)
{
  __builtin_strncpy (a->a, s, sizeof *a);   // -Wstringop-overflow (good)
}

struct B
{
  void (*pf)(void);
  char a[8];
};

void g (struct B *b, const char *s)
{
  __builtin_strncpy (b->a, s, sizeof *b);   // missing warning
}
z.c: In function ‘f’:
z.c:9:3: warning: ‘__builtin_strncpy’ writing 16 bytes into a region of size 8
overflows the destination [-Wstringop-overflow=]
   __builtin_strncpy (a->a, s, sizeof *a);   // -Wstringop-overflow (good)
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reply via email to