Ineffective Bounded Random
ID |
go.rand_intn_one |
Severity |
low |
Remediation Complexity |
simple |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
correctness, reliability |
Description
Reports a math/rand bounded-random call given the literal upper bound 1 — rand.Intn(1),
rand.Int31n(1) or rand.Int63n(1). Such a call can only ever return 0.
Rationale
The bounded functions in math/rand return a value in the half-open interval [0, n), so the
result is always >= 0 and < n. With n == 1 the only value in that range is 0, which makes
the call an ineffective attempt at generating a random number. It is almost always an off-by-one:
the bound passed should be the number of distinct values wanted, not an inclusive maximum.
func fn() {
a := rand.Intn(1) // FLAW — always returns 0
_ = a
}
Remediation
Pass the actual number of distinct values wanted as the bound, or remove the call if a constant result was intended.