Floating-point numbers can take on three exceptional values, infinity
, -infinity
and NaN
(not-a-number). These values are produced as a result of exceptional or otherwise unresolvable floating-point operations. These exceptional values can also be obtained directly from user input through methods such as Double.valueOf(String s)
. Failure to detect and handle such exceptional values can result in inconsistent behavior.
The method Double.valueOf(String s)
can return NaN
or an infinite double
, as specified by its contract. Programs should install checks to ensure that all floating-point inputs (especially those obtained from the user) are free of unexpected exceptional values. The methods Double.isNaN(double d)
and Double.isInfinite(double d)
can be used for this purpose.
NaN
values are particularly problematic because they are unordered. That is, the expression NaN == NaN
always returns false
. (see See guideline "NUM10-J. Do not attempt comparisons with NaN.").
Noncompliant Code Example
...
This compliant solution validates the floating-point input before using it. The value is tested to ensure that it is neither infinity
, -infinity
, nor NaN
.
...
Incorrect or missing validation of floating-point input can result in miscalculations and unexpected results, possibly leading to inconsistent program behavior and Denial denial of Service service (DoS).
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM11-J | low | probable | medium | P4 | L3 |
...
C Secure Coding Standard: "FLP04-C. Check floating point inputs for exceptional values"
C++ Secure Coding Standard: "FLP04-CPP. Check floating point inputs for exceptional values"
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup |
...
" ac:schema-version="1" ac:macro-id="4e3eccf5-e3db-4012-824e-cfb3a08b8b12"><ac:plain-text-body><![CDATA[ | [[IEEE |
...
754 |
...
https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE7542006 |
...
IEEE |
...
754] |
...
] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="34fb63d8-0245-4612-9a9d-71523d0a0326"><ac:plain-text-body><![CDATA[ | [[IEEE 1003.1, |
...
2004 |
...
https://www.securecoding.cert.org/confluence/display/seccode/AA.+C+References#AA.CReferences-IEEE1003 |
...
IEEE |
...
1003.1, |
...
2004]] |
...
]]></ac:plain-text-body></ac:structured-macro> |
...
NUM10-J. Do not attempt comparisons with NaN 03. Numeric Types and Operations (NUM) NUM12-J. Do not use floating point variables as loop counters