Constant length comparison¶
ID: go/constant-length-comparisonKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - correctness - external/cwe/cwe-129Query suites: - go-code-quality.qls - 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 operation uses a variable index but checks the length against a constant, this may indicate a logic error which could lead to an out-of-bounds access.
Recommendation¶
Inspect the code closely to determine whether the length should be compared to the index variable instead. For loops that iterate over every element, using arange loop is better than explicit index manipulation.
Example¶
The following example shows a method which checks whether slicexs is a prefix of sliceys:
packagemainfuncisPrefixOf(xs,ys[]int)bool{fori:=0;i<len(xs);i++{iflen(ys)==0||xs[i]!=ys[i]{returnfalse}}returntrue}
A loop using an index variablei is used to iterate over the elements ofxs and compare them to the corresponding elements ofys. However, the check to ensure thati is a valid index intoys is incorrectly specified aslen(ys)==0. Instead, the check should ensure thatlen(ys) is greater thani:
packagemainfuncisPrefixOfGood(xs,ys[]int)bool{fori:=0;i<len(xs);i++{iflen(ys)<=i||xs[i]!=ys[i]{returnfalse}}returntrue}
References¶
The Go Programming Language Specification:For statements.
The Go Programming Language Specification:Index expressions.
Common Weakness Enumeration:CWE-129.