https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82581
Bug ID: 82581
Summary: missing -Warray-bounds on writing past the end of a
member array
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: ---
When the bounds of a member array are exceeded in a loop that accesses the
member directly by its name, GCC issues a -Waggressive-loop-optimizations
warning mentioning the iteration of the loop in which the undefined behavior
occurs. But when the same access takes place indirectly through a pointer to
the member, no diagnostic is issued. Since the number of iterations of the
loop is known I would expect a -Warray-bounds warning (ideally in both cases,
even when no aggressive loop optimizations are performed).
As an aside, since the first iteration of a loop is usually thought of as
iteration 1 (not iteration zero), the iteration number referenced in the
-Waggressive-loop-optimizations warning is off by one. Since the array has
three elements, iteration 3 writes into the last (third) element, and it's
iteration four that has undefined behavior.
$ cat a.c && gcc -O2 -S -Wall -Warray-bounds -Wextra a.c
struct S
{
int a[3];
void (*pf)(void);
} x;
void f (void)
{
for (unsigned i = 0; i != sizeof x; ++i) // -Waggressive-loop-optimizations
x.a[i] = i;
}
void g (void)
{
int *p = x.a;
for (unsigned i = 0; i != sizeof x; ++i)
p[i] = i; // missing -Warray-bounds
}
a.c: In function âfâ:
a.c:10:12: warning: iteration 3 invokes undefined behavior
[-Waggressive-loop-optimizations]
x.a[i] = i;
~~~~~~~^~~
a.c:9:3: note: within this loop
for (unsigned i = 0; i != sizeof x; ++i)
^~~