Integer overflow
Assume integer arithmetic can overflow silently; guard sizes, counters, and bounds math deliberately.
Canonical guidance
- watch arithmetic that feeds allocation sizes, indexing, and protocol lengths
- check before the operation when overflow would be unsafe
- use fixed-width integers when size guarantees matter
Use when
- counters and accumulators
- byte-size calculations
- offsets and capacity math
Avoid
- assuming
intis always large enough - multiplying lengths without bounds checks
- converting between widths without considering truncation
Preferred pattern
const maxInt = int(^uint(0) >> 1)
func add(a, b int) (int, error) {
if b > 0 && a > maxInt-b {
return 0, errors.New("overflow")
}
return a + b, nil
}
Anti-pattern
- computing allocation sizes from untrusted input with unchecked arithmetic
Explanation: This anti-pattern is tempting because the math looks small and ordinary, but overflow often shows up exactly in boundary calculations.
Why
- overflow bugs corrupt correctness and can become security problems at boundaries
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Neglecting integer overflows (#18) - Teiva Harsanyi