...
The following noncompliant code accepts user data without first validating it.
Code Block | ||
---|---|---|
| ||
double currentBalance; /* User's cash balance */ void doDeposit(){ double val; scanf("%g", &val); currentBalance+=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 strings "INF", "INFINITY", or "NAN" (case insensitive) 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.
...
The following code first validates the input float before using it. The value is tested to ensure that it is neither infinity nor negative infinity nor NaN.
Code Block | ||
---|---|---|
| ||
double currentBalance; /* User's cash balance */ void doDeposit(){ double val; scanf("%g", &val); int k=isinf(x); if (k==1){ /* handle infinity error */ } if (k==-1){ /* handle negative infinity error */ } if(isnan(val)) /* test NaN */ { /* handle NaN error */ } currentBalance+=val; } |
Exceptions
...