Bug 82581 - missing -Warray-bounds on writing past the end of a member array
Summary: missing -Warray-bounds on writing past the end of a member array
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 8.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: diagnostic
Depends on:
Blocks: Warray-bounds
  Show dependency treegraph
 
Reported: 2017-10-17 15:01 UTC by Martin Sebor
Modified: 2020-06-10 17:47 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail: 10.1.0, 11.0, 8.4.0, 9.3.0
Last reconfirmed: 2020-06-10 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Martin Sebor 2017-10-17 15:01:38 UTC
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)
   ^~~
Comment 1 Martin Sebor 2020-06-10 17:47:32 UTC
Confirming with GCC 10 and 11.