g++ gives warning array subscript is above array bound... when I compile the following code (-Wall -O2)
#include <iostream>
#include <algorithm>
using namespace std;
int a[10];
int n;
int main(){
sort(a, a+n);
return 0;
}
but this code compiles without any warning:
#include <iostream>
#include <algorithm>
using namespace std;
int a[100];
int n;
int main(){
sort(a, a+n);
return 0;
}
Why does that happen?
When poking around on the net for issues related to
-Warray-boundsin GCC, it seems that problems with it crop up occasionally but those problems usually seem to be tied to very specific code scenarios. The feature seems to rely on the optimizer – this is why the-O2option is necessary for you to see the problem. (see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35903#c9 where it’s mentioned that “the reason this requires -O2 is that-Warray-boundsrequires VRP to warn” – VRP is Value Range Propagation). Minute differences in source can easily cause different behavior in the optimizer.Anyway, I think the more important thing about these problems with
-Warray-boundsis that they seem to also be tied to very specific compiler versions. For example, this bug (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949) reported against 4.4.3 (for all I know, this bug may be what’s causing the warning for you) is reported as working for 4.2.4, 4.5.1, and 4.6.0, while it’s also broken in 4.5.0. The fix for it apparently went into some 4.5.x version of the compiler.Anyway, the bottom line: if this is really a problems for you (ie., it’s not just a curiosity), you might want to consider one of the following workarounds/fixes:
-Wno-array-bounds