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

            Bug ID: 91679
           Summary: missing -Warray-bounds accessing a member array in a
                    local buffer
           Product: gcc
           Version: 9.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

It's relatively common to declare a character buffer on the stack and use it as
an object of some aggregate type such as a struct, including one with a
trailing array treated as a flexible array member (see for example PR 48795). 
Hacks like this are easy to make mistakes in, and introduce a stack buffer
overflow.  Unfortunately, because the cast from the type of the buffer to the
aggregate pointer obscures the true bounds of the allocated space, GCC doesn't
issue a warning for out-of-bounds accesses.

$ cat a.c && gcc -O2 -S -Wall -Wextra a.c
struct A
{
  int n;
  short a[1];
};

static void f (struct A *p)
{
  p->a[0] = 0;   // in bounds of struct A
  p->a[1] = 1;   // same
  p->a[2] = 2;   // beyond struct A but in bounds of buffer a
  p->a[3] = 3;   // same
  p->a[4] = 4;   // out of bounds, missing warning
}

void g (void*);

void h (void)
{
  char a [sizeof (struct A) + 2 * sizeof (short)];
  f ((struct A*)a);
  g (a);
}

Reply via email to