Off-by-one comparison against length¶
ID: go/index-out-of-boundsKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctness - external/cwe/cwe-193Query suites: - go-security-and-quality.qls
Click to see the query in the CodeQL repository
Indexing operations on arrays, slices or strings should use an index at most one less than the length. If the index to be accessed is checked for being less than or equal to the length (<=), instead of less than the length (<), the index could be out of bounds.
Recommendation¶
Use less than (<) rather than less than or equals (<=) when comparing a potential index against a length. For loops that iterate over every element, a better solution is to use arange loop instead of looping over explicit indexes.
Example¶
The following example shows a method which checks whether a value appears in a comma-separated list of values:
packagemainimport"strings"funccontainsBad(searchNamestring,namesstring)bool{values:=strings.Split(names,",")// BAD: index could be equal to lengthfori:=0;i<=len(values);i++{// When i = length, this access will be out of boundsifvalues[i]==searchName{returntrue}}returnfalse}
A loop using an index variablei is used to iterate over the elements in the comma-separated list. However, the terminating condition of the loop is incorrectly specified asi<=len(values). This condition holds wheni is equal tolen(values), but the accessvalues[i] in the body of the loop will be out of bounds in this case.
One potential solution would be to replacei<=len(values) withi<len(values). A better solution is to use arange loop instead, which avoids the need for explicitly manipulating the index variable:
packagemainimport"strings"funccontainsGood(searchNamestring,namesstring)bool{values:=strings.Split(names,",")// GOOD: Avoid using indexes, use range loop insteadfor_,name:=rangevalues{ifname==searchName{returntrue}}returntrue}
References¶
The Go Programming Language Specification:For statements.
The Go Programming Language Specification:Index expressions.
Common Weakness Enumeration:CWE-193.