Go

Go

Made by DeepSource

Risky constant length comparison GO-S1007

Security
Major
Autofix

Explicit indexing operations should be carefully vetted; there could be logical errors leading to index out-of-bounds access and then runtime panic.

If the operation uses a variable index but checks the length against a constant, it is risky. Hence, the length should be compared to the index instead.

Bad practice

func hasPrefix(s, prefix []int) bool {
    for i := 0; i < len(prefix); i++ {
        if len(s) == 0 || prefix[i] != s[i] { // Logical error, try `len(s) <= i`.
            return false
        }
    }
    return true
}

Recommended

func hasPrefix(s, prefix []int) bool {
    for i := 0; i < len(prefix); i++ {
        if len(s) <= i || prefix[i] != s[i] { // Logical error, try `len(s) <= i`.
            return false
        }
    }
    return true
}

References