Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The following noncompliant code accepts user data without first validating it.

Code Block
bgColor#FFCCCC
 
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.

Here, for example, entering "nan" for val would force currentBalance to also equal "nan", corrupting its value. If this value is used elsewhere for calculations, every resulting value would also be NaN, possibly destroying important data.

Compliant Code Example

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
bgColor#ccccff

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

Occasionally, NaN or infinity may be acceptable or expected inputs to a program. If this is the case, then explicit checks may not be necessary. Such programs must, however, be prepared to handle these inputs gracefully and not blindly use them in mathematical expressions where they are not appropriate.

...