public inbox for gcc-bugs@sourceware.org
help / color / mirror / Atom feed
* [Bug c/108770] New: Spurious -Warray-bounds at -O2 (gcc >= 12)
@ 2023-02-13 10:20 andrew.jones at vector dot com
2023-02-13 10:58 ` [Bug c/108770] " rguenth at gcc dot gnu.org
0 siblings, 1 reply; 2+ messages in thread
From: andrew.jones at vector dot com @ 2023-02-13 10:20 UTC (permalink / raw)
To: gcc-bugs
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.
^ permalink raw reply [flat|nested] 2+ messages in thread
end of thread, other threads:[~2023-02-13 10:58 UTC | newest]
Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-02-13 10:20 [Bug c/108770] New: Spurious -Warray-bounds at -O2 (gcc >= 12) andrew.jones at vector dot com
2023-02-13 10:58 ` [Bug c/108770] " rguenth at gcc dot gnu.org
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).