https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85398
Bug ID: 85398 Summary: g++ reports "array subscript is above array bounds" when it cannot be sure Product: gcc Version: 6.4.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: other Assignee: unassigned at gcc dot gnu.org Reporter: patrickdepinguin at gmail dot com Target Milestone: --- In following test program: ------------------------------ #define NB_DEV 1 extern unsigned int max; unsigned long left[NB_DEV]; unsigned long right[NB_DEV]; void foo() { unsigned int i; for (i=1; i < max; i++) left[i] = right[i-1]; } ------------------------------ compiled with: $(CXX) -Werror -Wall -O2 -c reprod.cc g++ gives following warning/error: reprod.cc: In function 'void foo()': reprod.cc:13:13: error: array subscript is above array bounds [-Werror=array-bounds] left[i] = right[i-1]; ~~~~~~^ cc1plus: all warnings being treated as errors make: *** [Makefile:4: all] Error 1 While there _could_ be an array overflow, g++ cannot know for sure because the loop boundary 'max' is an external variable. The code is perfectly fine in case max == 1. In that case, the loop does nothing. This is a reduced version of real code where the arrays left and right are dimensioned to some maximum value NB_DEV, and 'max' will be at most that NB_DEV but possibly smaller. We are thus sure there will not be an array overflow. Going back to the reproduction code above, if you change NB_DEV to 2 (for example), no warning is thrown, even though there could still be an overflow in case max == 5, for example. According to me, no warning should be thrown because g++ cannot surely say there is a problem. Same problem is seen if you compile this as C code rather than C++. Problem is not seen with -O1, only with -O2 or -O3. This problem was tested with gcc 6.4.0 (x86_64), gcc 6.3.0 (armeb), gcc 5.4.0 (armeb) and gcc 4.9.4 (armeb).