Division or modulo by the literal zero
ID |
objectivec.correctness.division_by_zero |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Numeric Operation |
Language |
Objective-C |
Description
Reports a /, %, /= or %= whose right-hand operand is written as the integer literal 0. Only the literal is reported - a floating-point 0.0, a hexadecimal 0x0, a named constant that happens to expand to zero, and a variable that merely could be zero are all left alone, because deciding those needs value tracking this matcher does not have.
Rationale
Integer division and modulo by zero are undefined behaviour in C, and on ARM and Intel the processor raises SIGFPE, so the app does not return a strange number - it dies. Because the denominator is written into the source rather than computed, the fault does not depend on input or timing: every execution that reaches the line terminates. A literal zero here is almost always a placeholder that was never filled in, or the residue of an edit that removed the variable the expression used to divide by.
The following code illustrates the pattern detected by this rule:
@implementation Meter
- (NSInteger)averageOf:(NSInteger)total {
// FLAGGED: Division or modulo by the literal zero
return total / 0;
}
- (NSInteger)currentCount { return 1; }
@end
Remediation
Put the real denominator back, or - if the expression can legitimately be handed zero - branch on it and give the zero case its own answer. Where the value is a floating-point quantity and infinity is acceptable, make that explicit by using double operands, which yield inf rather than a signal.