...
This noncompliant code example accepts user data without validating it.
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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