https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108770
Bug ID: 108770
Summary: Spurious -Warray-bounds at -O2 (gcc >= 12)
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: andrew.jones at vector dot com
Target Milestone: ---
I think this might be a duplicate of some other cases, but this also seems
"simpler" and more surprising about the -Warray-bounds:
```
extern void put(int i);
int check_idx(int i) {
if (i > 1)
put(i);
return i;
}
const char *arr[] = {"A", 0};
void init() {
int i = 0;
while (arr[check_idx(i)] != 0) {
if (arr[check_idx(i)]) {}
i++;
}
}
```
On Godbolt, and with `-Warray-bounds -Werror`, we get:
* GCC 11.3, -O2: compiles
* GCC 11.3, -O3: compiles
* GCC 12.1, -O2: does not compile
* GCC 12.1, -O3: does not compile
* GCC "trunk" (22ba8570e6343e10e4a82e837166e181a1abb21b-binutils-2.38),
-O2: does not compile
* GCC "trunk" (22ba8570e6343e10e4a82e837166e181a1abb21b-binutils-2.38),
-O3: does not compile
The error looks like:
```
<source>: In function 'init':
<source>:9:13: error: array subscript 2 is above array bounds of 'const char
*[2]' [-Werror=array-bounds=]
9 | while (arr[check_idx(i)] != 0) {
| ~~~^~~~~~~~~~~~~~
<source>:6:13: note: while referencing 'arr'
6 | const char *arr[] = {"A", 0};
| ^~~
cc1: all warnings being treated as errors
Compiler returned: 1
```
As far as I can tell, this program is "well formed": the first iteration of the
loop (`i=0`), then `arr[i] != 0`; on the second iteration of the loop (`i=1`),
`arr[i] == 0`, so we terminate.
Basically, "by inspection", it is unclear to me how GCC decides on the array
index being possible at 2.
Interestingly, if you change:
```
if (i > 1)
```
in `check_idx` to be anything *other* than the `length of arr - 1`, then the
warning goes away.
Equally, if you add an extra element to `arr` (e.g., `arr[] = {"A", "A", 0}`),
then you now need `i > 2` to trigger the warning.