Versions Compared

Key

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

...

This noncompliant code example accepts user data without validating it.

Code Block
bgColor#FFCCCC

double currentBalance; // User's cash balance

void doDeposit(String userInput) {
  double val = 0;
  try {
    val = Double.valueOf(userInput);
  } catch (NumberFormatException e) {
    // Handle input format error
  }

  if (val >= Double.MAX_VALUE - currentBalance) {
    // Handle range error
  }

  currentBalance += val;
}

...

This compliant solution validates the floating-point input before using it. The value is tested to ensure that it is neither infinity, -infinity, nor NaN.

Code Block
bgColor#ccccff

double currentBalance; // User's cash balance

void doDeposit(String userInput){
  double val = 0;
  try {
    val = Double.valueOf(userInput);
  } catch (NumberFormatException e) {
    // Handle input format error
  }

  if (Double.isInfinite(val)){
    // Handle infinity error
  }

  if (Double.isNaN(val)) {
    // Handle NaN error
  }

  if (val >= Double.MAX_VALUE - currentBalance) {
    // Handle range error
  }
  currentBalance += val;
}

...

Automated detection is infeasible in the general case. It could be possible to develop a taint-like analysis that detects many interesting cases.

Related Guidelines

Bibliography