Impossible Len Or Cap Check

ID

go.impossible_len_cap_check

Severity

high

Remediation Complexity

simple

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Go

Tags

CWE:570, reliability, suspicious

Description

Reports a comparison of len(…​) or cap(…​) against the literal 0 that can never change outcome: len(s) < 0 and cap(s) < 0 are always false, and len(s) >= 0 and cap(s) >= 0 are always true.

Rationale

Both len and cap always return a non-negative value, so comparing them as if they could be negative is dead code. It usually signals that the author meant == 0 (empty) or > 0 (non-empty). The check fires only for the literal 0; comparisons against 1 or a named constant are left alone.

func fn(s []int) {
    if len(s) < 0 { // FLAW — always false
        println("test")
    }
    _ = cap(s) >= 0 // FLAW — always true
    if len(s) == 0 { // OK — empty check
    }
}

Remediation

Replace the comparison with a meaningful one (== 0 for empty, > 0 for non-empty), or remove the dead branch.