...
NaN
values are particularly problematic because the expression NaN == NaN
always returns false
(See FLP02-J. Do not attempt comparisons with NaN). In general, any comparisons with NaN
return false
, and all arithmetic functions on NaN
inputs simply propagate the taint throughout the code. Hence, just Just one occurrence of a NaN
value can effectuate regressions within other code segments.
...
Code Block | ||
---|---|---|
| ||
double currentBalance; /*/ User's cash balance */ void doDeposit(String userInput){ double val; try { val = Double.valueOf(userInput); } catch(NumberFormatException e) { //* Handle input format error*/ } if(val >= Double.MAX_VALUE - currentBalance) { /*/ Handle range error*/ } currentBalance += val; } |
This can be a problem if an invalid value is entered for val
and subsequently used in calculations or as control values. The user could, for example, input the strings infinity
or NaN
on the command line, which would be parsed by Double.valueOf(String s)
into the floating-point representations of either infinity
or NaN
. All subsequent calculations using these values would be invalid, possibly causing runtime exceptions or enabling denial of service (DoS) attacks.
Here, for exampleIn this compliant solution, entering NaN
for val
would force currentBalance
to also equal NaN
, corrupting its value. If this value is used in other expressions, every resulting value would also be will become NaN
, possibly destroying corrupting important data.
Compliant Solution
The following code first This compliant solution validates the floating point input before using it. The value is tested to ensure that it is neither infinity
, negative infinity
nor NaN
.
Code Block | ||
---|---|---|
| ||
double currentBalance; //* User's cash balance */ void doDeposit(String s){ double val; try { val = Double.valueOf(userInput); } catch(NumberFormatException e) { /*/ Handle input format error*/ } if (Double.isInfinite(val)){ //* handleHandle infinity error */ } if (Double.isNaN(val)) { //* handleHandle NaN error */ } if(val >= Double.MAX_VALUE - currentBalance) { /*/ Handle range error*/ } currentBalance += val; } |
Exceptions
EX1: Occasionally, NaN
or infinity may be acceptable as expected inputs to a program. If this is the case, then In such cases, explicit checks may not be necessary. Such However, such programs must , however, be prepared to handle these inputs gracefully and should not allow the propagation of taint to other values by using them in mathematical expressions where they are inappropriate.
...