Array index out of bounds¶
ID: java/index-out-of-boundsKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctness - exceptions - external/cwe/cwe-193Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
When accessing an array element, one must ensure that the index is less than the length of the array. Using an index that is greater than or equal to the array length causes anArrayIndexOutOfBoundsException.
Recommendation¶
Ensure that the index is less than the array length.
Example¶
The following example causes anArrayIndexOutOfBoundsException in the final loop iteration.
for(inti=0;i<=a.length;i++){// BADsum+=a[i];}
The condition should be changed as follows to correctly guard the array access.
for(inti=0;i<a.length;i++){// GOODsum+=a[i];}
References¶
Java API Specification:ArrayIndexOutOfBoundsException.
Common Weakness Enumeration:CWE-193.