CodeQL documentation

Array index out of bounds

ID: java/index-out-of-bounds
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - quality
   - 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

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy