https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104165
Bug ID: 104165
Summary: Incorrectly identifying array bounds with -O2
-Werror=array-bounds
Product: gcc
Version: 12.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: kbrabml at gmail dot com
Target Milestone: ---
In file included from /home/install/include/c++/12.0.1/algorithm:61,
from repro.cpp:1:
In function ‘void std::__final_insertion_sort(_RandomAccessIterator,
_RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare =
__gnu_cxx::__ops::_Iter_comp_iter<bar(int, int)::<lambda(int, int)> >]’,
inlined from ‘void std::__sort(_RandomAccessIterator,
_RandomAccessIterator, _Compare) [with _RandomAccessIterator = int*; _Compare =
__gnu_cxx::__ops::_Iter_comp_iter<bar(int, int)::<lambda(int, int)> >]’ at
/home/install/include/c++/12.0.1/bits/stl_algo.h:1940:31,
inlined from ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter =
int*; _Compare = bar(int, int)::<lambda(int, int)>]’ at
/home/install/include/c++/12.0.1/bits/stl_algo.h:4853:18,
inlined from ‘int bar(int, int)’ at repro.cpp:17:14,
inlined from ‘int foo(int)’ at repro.cpp:25:13:
/home/install/include/c++/12.0.1/bits/stl_algo.h:1849:32: error: array
subscript 16 is outside array bounds of ‘unsigned char [16]’
[-Werror=array-bounds]
1849 | std::__insertion_sort(__first, __first + int(_S_threshold),
__comp);
|
~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In function ‘int bar(int, int)’,
inlined from ‘int foo(int)’ at repro.cpp:25:13:
repro.cpp:4:7: note: at offset 64 into object ‘f.140’ of size 16
4 | int f[l];
| ^
cc1plus: all warnings being treated as errors
make: *** [Makefile:5: all] Error 1
Getting the above bogus warning when compiling following reproducer
#include <algorithm>
static int bar(int n, int l) { // make function non-static and warning goes
away
int f[l];
int x = 0;
int r = n;
for (; x < l;) {
if (r) {
x = l;
} else { // Take out this else and the warning goes away
r = 1;
}
}
if (r == 1) { // Take out this branch and the warning goes away
std::sort(f, f + x,
[](int a, int b) { return a > b; });
}
return 1;
}
int foo(int n) {
return bar(n, 4);
}
Compiled with HEAD of GCC (as of 20/01/2021)
g++ -c -march=armv8-a -Werror -Wall -O2 repro.cpp
The compiler sees that the size of the array is 4 ints (16-bytes), but doesn't
see that x <= 4, so that no array out of bounds should occur. Workaround is to
use malloc for the array.