Versions Compared

Key

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

...

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

Code Block
bgColor#ccccff
if (a == b) {
  /* ... */
}
else if (a == c) {
  /* ... */
}
else {
  /* handleHandle error condition */
}

Noncompliant Code Example (Switch)

...

Code Block
bgColor#ccccff
switch(x) {
  case 0: foo(); break;
  case 1: bar(); break;
  default: /* handleHandle error */ break;
} 

Noncompliant Code Example (Zune 30)

...

Code Block
bgColor#FFCCCC
final static int ORIGIN_YEAR = 1980;
long days = /* numberNumber of days since January 1, 1980 */
int year = ORIGIN_YEAR;
/* ... */

while (days > 365) {
  if (IsLeapYear(year)) {
    if (days > 366) {
      days -= 366;
      year += 1;
    }
  }
  else {
    days -= 365;
    year += 1;
  }
}

...

This proposed rewrite is provided by "A lesson Lesson on infinite loops"Infinite Loops" by Bryant Zadegan. The loop is guaranteed to exit, as days decreases for each iteration of the loop, unless the while condition fails, in which case the loop terminates.

Code Block
bgColor#ccccff
final static int ORIGIN_YEAR = 1980;
long days = /* numberNumber of days since January 1, 1980 */
int year = ORIGINYEAR;
/* ... */

int daysThisYear = (IsLeapYear(year) ? 366 : 365);
while (days > daysThisYear) {
  days -= daysThisYear;
  year += 1;
  daysThisYear = (IsLeapYear(year) ? 366 : 365);
}

...

Failing to take into account all possibilities within a logic statement can lead to a corrupted running state, potentially resulting in unintentional information disclosure or abnormal termination.

Related Guidelines 

...

:2013Switch Statements and Static Analysis

...

[CLL]

Bibliography

...

§2.7.2, "Errors of Omission and Addition"
[Viega 2005]

...

§5.2.17, "Failure to Account for Default Case in Switch"
[Zadegan 2009]A Lesson on Infinite Loops  (for analysis on the Zune 30 bug)

 

...