Kingdom: Code Quality

Poor code quality leads to unpredictable behavior. From a user's perspective that often manifests itself as poor usability. For an attacker it provides an opportunity to stress the system in unexpected ways.

Code Correctness: Comparison with NaN

Abstract
Making a comparison with NaN is always an error.
Explanation
When a comparison is made to NaN it is always evaluated as false, except for the != operator, which always evaluates to true since NaN is unordered.

Example 1: The following tries to make sure a variable is not NaN.


...
if (result == Double.NaN){
//something went wrong
throw new RuntimeException("Something went wrong, NaN found");
}
...


This attempts to verify that result is not NaN, however using the operator == with NaN always results in a value of false, so this check will never throw the exception.
References
[1] NUM07-J. Do not attempt comparisons with NaN CERT
[2] Java Language Specification Chapter 4. Types, Values, and Variables Oracle
[3] INJECT-9: Prevent injection of exceptional floating point values Oracle
[4] Standards Mapping - Common Weakness Enumeration CWE ID 486
desc.structural.java.code_correctness_comparison_with_nan