Division By Zero
ID |
go.division_by_zero |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a division (/) or remainder (%) whose right-hand operand is the literal 0 —
for example x / 0 or x % 0. With integer operands this is a compile-time error for a
constant divisor and a runtime panic otherwise; with floating-point operands it produces
+Inf, -Inf or NaN. Either way a literal zero divisor is a bug.
Rationale
A literal 0 on the right of / or % is never intentional — it is a typo, a placeholder
that was never filled in, or a constant that collapsed to zero. The Go compiler catches some
integer cases, but not all (for instance when the dividend is a non-constant), so the panic
reaches runtime. Flagging the literal divisor makes the mistake obvious immediately.
y := x / 0 // FLAW — division by literal zero
z := x % 0 // FLAW — remainder by literal zero
y := x / 2 // OK — non-zero divisor
z := x % n // OK — divisor is a variable
Remediation
Use a non-zero divisor. If the divisor can legitimately be zero at runtime, guard the operation with an explicit zero check before dividing.