我从GCC收到以下代码的警告:
#include <math.h>
int init_tables() {
int retval = 0;
for(unsigned row = 0; row < 65536; ++row) {
unsigned line[4] = {
(row >> 0) & 0xf,
(row >> 4) & 0xf,
(row >> 8) & 0xf,
(row >> 12) & 0xf
};
float monotonicity_left = 0;
float monotonicity_right = 0;
for (int i = 1; i < 4; ++i) {
if (line[i-1] > line[i]) {
monotonicity_left += pow(line[i-1], 4) - pow(line[i], 4);
} else {
monotonicity_right += pow(line[i], 4) - pow(line[i-1], 4);
}
}
int i;
for(i=0; i<3; i++) {
if(line[i] == 0) {
line[i] = line[i+1];
break;
} else if(line[i] == 1 && line[i+1] == 2) {
line[i] = 3;
break;
} else if(line[i] == 2 && line[i+1] == 1) {
line[i] = 3;
break;
} else if(line[i] == line[i+1] && line[i] >= 3) {
if(line[i] != 15) {
line[i]++;
}
break;
}
}
if(i == 3)
continue;
/* fold to the left */
for(int j=i+1; j<3; j++)
line[j] = line[j+1];
line[3] = 0;
int result = (line[0] << 0) |
(line[1] << 4) |
(line[2] << 8) |
(line[3] << 12);
retval += row ^ result;
}
return retval;
}
道歉;这是最小化的测试用例(删除几乎所有内容,例如pow
或if
语句会导致警告消失。
这是使用g++ -O3 -Wall -c -o /dev/null test.cpp
编译的。在4.8.5和5.3.0(MacPorts)和4.8.4(Ubuntu 14.04)上,结果是以下警告:
test.cpp: In function 'int init_tables()':
test.cpp:48:31: warning: array subscript is above array bounds [-Warray-bounds]
line[j] = line[j+1];
^
test.cpp:48:31: warning: array subscript is above array bounds [-Warray-bounds]
据我所知,代码是正确的 - for循环导致i
取0到3之间的值,if(i == 3)
应该确保j
只需要从1到2的值。这种理解是正确的,还是我的代码中有错误?