常量长度比较¶
ID: go/constant-length-comparison
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- correctness
Query suites:
- go-security-and-quality.qls
对数组、切片或字符串的索引操作使用的索引应最多比长度小一。如果操作使用变量索引但根据常量检查长度,则这可能表示逻辑错误,从而导致越界访问。
建议¶
仔细检查代码,以确定是否应改为将长度与索引变量进行比较。对于迭代每个元素的循环,使用 range
循环比显式索引操作更好。
示例¶
以下示例显示了一个方法,该方法检查切片 xs
是否是切片 ys
的前缀
package main
func isPrefixOf(xs, ys []int) bool {
for i := 0; i < len(xs); i++ {
if len(ys) == 0 || xs[i] != ys[i] {
return false
}
}
return true
}
使用索引变量 i
的循环用于迭代 xs
的元素并将它们与 ys
的相应元素进行比较。但是,确保 i
是 ys
的有效索引的检查被错误地指定为 len(ys) == 0
。相反,检查应确保 len(ys)
大于 i
package main
func isPrefixOfGood(xs, ys []int) bool {
for i := 0; i < len(xs); i++ {
if len(ys) <= i || xs[i] != ys[i] {
return false
}
}
return true
}