Division by Zero
Definition
Division by zero is a logic software bug that in most cases causes a run-time error when a number is divided by zero.
Program Behavior
Whether or not this run-time error occurs depends on a number of factors: the language of the program and its development platform and the types of dividends.
According to section 5.6 of the C++ language standard, if operators "/" and "%" have 0 as the second operand, undefined behavior occurs.
When trying to divide a number by an integer zero on a processor of the x86 and x86_64 processor families, a hardware exception is generated (by vector 0); accordingly, a C/C++ program compiled into machine code will crash when executing this operation.
At the same time, if the zero-variable is a real one, then, according to the IEEE 754 standard, the result is a real number "plus infinity" or "minus infinity" (the standard also specifies that zero is a signed number) in case of a non-zero numerator, and a "NaN" (not a number) in case of the 0/0 indetermination (the Microsoft Visual C++ compiler returns the "indeterminate" number specific to the x86 platform).
Note that the variable does not necessarily have to contain zero: it may occur as a result of rounding of values, which is called an arithmetic underflow, when the result of a rounding operation is a number whose value is under machine precision. The result in this case is assumed as equal to 0.
Tracking Zero Divide Errors
Divide-by-zero bugs can be tracked by some compilers (for instance, Microsoft Visual C++) and static analyzers.
One should be especially attentive when dividing a number by a variable which serves as a loop iterator, for one may easily forget that it should at some point go through the zero value. Static analyzers use a special diagnostic to check that (the V609 diagnostic in the PVS-Studio).
References
- Wikipedia. Division by zero.
- IEEE. IEEE Standard for Floating-Point Arithmetic (IEEE 754).
- MSDN. Know Your Bugs: Three Kinds of Programming Errors
- Stack Overflow discussion. C++ : Catch a divide by zero error, Catching exception: divide by zero.
0