数组索引超出范围¶
ID: java/index-out-of-bounds
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- correctness
- exceptions
- external/cwe/cwe-193
Query suites:
- java-security-and-quality.qls
访问数组元素时,必须确保索引小于数组的长度。使用大于或等于数组长度的索引会导致 ArrayIndexOutOfBoundsException
。
建议¶
确保索引小于数组长度。
示例¶
以下示例在最后一次循环迭代中导致 ArrayIndexOutOfBoundsException
。
for (int i = 0; i <= a.length; i++) { // BAD
sum += a[i];
}
应按如下方式更改条件,以正确保护数组访问。
for (int i = 0; i < a.length; i++) { // GOOD
sum += a[i];
}
参考¶
Java API 规范:ArrayIndexOutOfBoundsException。
常见弱点枚举:CWE-193。