Floating-point numbers can take on two classes of exceptional values; infinity and NaN (not-a-number). These values are returned as the result of exceptional or otherwise unresolvable floating point operations. (See also: \[<span style="color: #003366"><span style="text-decoration: underline; ">FLP32-C. Prevent or detect domain and range errors in math functions|https://www.securecoding.cert.org/confluence/display/seccode/FLP32-C.+Prevent+or+detect+domain+and+range+errors+in+math+functions</span></span>\]). Additionally, they can be directly input by a user by scanf or similar functions. Failure to detect and handle such values can result in undefined FLP32-C. Prevent or detect domain and range errors in math functions). Additionally, they can be directly input by a user by scanf or similar functions. Failure to detect and handle such values can result in undefined behavior. Wiki Markup
NaN values are particularly problematic, as the expression NaN==NaN (for every possible value of NaN) returns false. It is possible to test that a variable x is NaN by checking that (x==x) evaluates to false. Any comparisons made with NaN as one of the arguments returns false, and all arithmetic functions on NaNs simply propagate them through the code. Hence, a NaN entered in one location in the code and not properly handled could potentially cause problems in other, more distant sections.
Formatted-input functions such as sscanf will accept the values INFINITY or NAN (not case sensitive) as valid inputs for the %f format specification, allowing malicious users to feed them directly to a program. Programs should therefore check to ensure that all input floating point values (especially those controlled by the user) do not have either of these values if doing so would be inappropriate.
...
The following noncompliant code accepts user data without first validating it.
Panel | ||||
---|---|---|---|---|
| ||||
double val; scanf("%g", &val); |
This can be a problem if an invalid value is entered for val and subsequently used for calculations or as control values. The user could, for example, input the values "INF", "INFINITY", or "NAN" on the command line, which would be parsed by scanf into the floating-point representations of infinity and NaN. All subsequent calculations using these values would be invalid, possibly crashing the program and enabling a DOS attack.
Compliant Code Example
The following code first validates the input float before using it. The value is tested to ensure that it is within the acceptable range of MIN_VAL to MAX_VAL (and is therefore neither infinity nor negative infinity). Note the use of "val!=val" to test for NaN.
Panel | ||||||
---|---|---|---|---|---|---|
| ||||||
double val; scanf("%g", &val); if(val<MIN_VAL || val>MAX_VAL) { // handle range error } if(val!=val) //test NaN { // handle NaN error } |
...