You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 12 Next »

Software vulnerabilities can result when a programmer fails to consider all possible data states.

Non-Compliant Code Example

This example fails to test for conditions where a is neither b nor c. This may be the correct behavior in this case, but failure to account for all the values of a may result in logic errors if a unexpectedly assumes a different value.

...
if (a == b) {
  ...
}
else if (a == c) {
  ...
}
...

Compliant Solution

This compliant solution explicitly checks for the unexpected condition and handles it appropriately.

...
if (a == b) {
  ...
}
else if (a == c) {
  ...
}
else {
  /* handle error condition */
}
...

Non-Compliant Code Example

This non-compliant code example fails to consider all possible cases. This may be the correct behavior in this case, but failure to account for all the values of widget_type may result in logic errors if widget_type unexpectedly assumes a different value. This is particularly problematic in C, because an identifier declared as an enumeration constant has type int. Therefore, a programmer can accidentally assign an arbitrary integer value to an enum type as shown in this example.

...
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type;

widget_type = 45; 
  
switch (widget_type) {
  case WE_X: 
    ...
    break;
  case WE_Y: 
    ...
    break;
  case WE_Z: 
    ...
    break;
}   
...

Implementation Details

Microsoft Visual C++ .NET with /W4 does not warn when assigning an integer value to an enum type, or when the switch statement does not contain all possible values of the enumeration.

Compliant Solution

This compliant solution explicitly checks for the unexpected condition by adding a default clause to the switch statement.

...
enum WidgetEnum { WE_X, WE_Y, WE_Z } widget_type;

widget_type = WE_X; 
  
switch (widget_type) {
  case WE_X: 
    ...
    break;
  case WE_Y: 
    ...
    break;
  case WE_Z: 
    ...
    break;
  default:
    /* handle error condition */
    break;
}   
...

References

Hatton 95 Section 2.7.2 Errors of omission and addition

  • No labels