CodeQL documentation

Array index out of bounds

ID: java/index-out-of-bounds
Kind: problem
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
   - exceptions
   - external/cwe/cwe-193
Query 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 an ArrayIndexOutOfBoundsException.

Recommendation

Ensure that the index is less than the array length.

Example

The following example causes an ArrayIndexOutOfBoundsException in the final loop iteration.

for (int i = 0; i <= a.length; i++) { // BAD
  sum += a[i];
}

The condition should be changed as follows to correctly guard the array access.

for (int i = 0; i < a.length; i++) { // GOOD
  sum += a[i];
}

References