Errors in C, C++, and other programming languages often Software vulnerabilities can result when a programmer fails to consider all possible data states.
...
Noncompliant Code Example (if
Chain)
This noncompliant code example fails to test for conditions where a
is neither b
nor c
. This behavior may be the correct behavior in this case, but failure to account for all the values of a
may can result in logic errors if a
unexpectedly assumes a different value.
Code Block | ||||
---|---|---|---|---|
| ||||
... if (a == b) { /* ... */ } else if (a == c) { /* ... */ } ... |
Compliant Solution (if
Chain)
This compliant solution explicitly checks for the unexpected condition and handles it appropriately.:
Code Block | ||||
---|---|---|---|---|
| ||||
... if (a == b) { /* ... */ } else if (a == c) { /* ... */ } else { /* handleHandle error condition */ } ... |
...
Noncompliant Code Example (switch
)
This non-compliant noncompliant code example fails to consider all possible cases. This may be the correct behavior in this case, but failure Failure to account for all the valid values of widget_ type may Color
will 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 accidently assign an arbitrary integer value to an enum
type as shown in this example. a logic error. Because valid values of an enumerated type include all those of its underlying integer type, unless enumeration constants have been provided for all those values, the default
label is appropriate and necessary.
Code Block | ||||
---|---|---|---|---|
| ||||
typedef enum { Red, Green, Blue } Color;
const char* f(Color c) {
switch (c) {
case Red: return "Red";
case Green: return "Green";
case Blue: return "Blue";
}
}
void g() {
Color unknown = (Color)123;
puts(f(unknown));
} | ||||
Code Block | ||||
...
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 (switch
)
This compliant solution explicitly checks for the unexpected condition by adding a default
clause to the switch statement.
Code Block |
---|
...
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
takes care to provide the default
label to handle all valid values of type Color
:
Code Block | ||||
---|---|---|---|---|
| ||||
typedef enum { Red, Green, Blue } Color;
const char* f(Color c) {
switch (c) {
case Red: return "Red";
case Green: return "Green";
case Blue: return "Blue";
default: return "Unknown color"; /* Necessary */
}
}
|
Note that adding a default case to a switch
statement, even when all possible switch
labels are specified, is an exception (MSC07-C-EX1) to MSC07-C. Detect and remove dead code.
An alternative compliant solution to the noncompliant code example is to provide a return
statement after the switch
statement. Note, however, that this solution may not be appropriate in all situations.
Code Block | ||||
---|---|---|---|---|
| ||||
typedef enum { Red, Green, Blue } Color;
const char* f(Color c) {
switch (c) {
case Red: return "Red";
case Green: return "Green";
case Blue: return "Blue";
}
return "Unknown color"; /* Necessary */
}
|
Historical Discussion
This practice has been a subject of debate for some time, but a clear direction has emerged.
Originally, the consensus among those writing best practices was simply that each switch
statement should have a default
label. Eventually, emerging compilers and static analysis tools could verify that a switch
on an enum
type contained a case
label for each enumeration value, but only if no default
label existed. This led to a shift toward purposely leaving out the default
label to allow static analysis. However, the resulting code was then vulnerable to enum
variables being assigned int
values outside the set of enum
values.
These two practices have now been merged. A switch
on an enum
type should now contain a case
label for each enum
value but should also contain a default
label for safety. This practice does not add difficulty to static analysis.
Existing implementations are in transition, with some not yet analyzing switch
statements with default
labels. Developers must take extra care to check their own switch
statements until the new practice becomes universal.
Noncompliant Code Example (Zune 30)
This noncompliant code example shows incomplete logic when converting dates. The code appeared in the Zune 30 media player, causing many players to lock up on December 30, 2008, at midnight PST. This noncompliant code example comes from the ConvertDays
function in the real-time clock (RTC) routines for the MC13783 PMIC RTC. It takes the number of days since January 1, 1980, and computes the correct year and number of days since January 1 of the correct year.
The flaw in the code occurs when days
has the value 366 because the loop never terminates. This bug manifested itself on the 366th day of 2008, which was the first leap year in which this code was active.
Code Block | ||||
---|---|---|---|---|
| ||||
#define ORIGINYEAR 1980
UINT32 days = /* Number of days since January 1, 1980 */
int year = ORIGINYEAR;
/* ... */
while (days > 365) {
if (IsLeapYear(year)) {
if (days > 366) {
days -= 366;
year += 1;
}
}
else {
days -= 365;
year += 1;
}
}
|
Compliant Solution (Zune 30)
The following proposed rewrite is provided at http://winjade.net/2009/01/lesson-on-infinite-loops. The loop is guaranteed to exit, because days
decreases for each iteration of the loop, unless the while
condition fails and the loop terminates.
Code Block | ||||
---|---|---|---|---|
| ||||
#define ORIGINYEAR 1980
UINT32 days = /* Input parameter */
int year = ORIGINYEAR;
/* ... */
int daysThisYear = (IsLeapYear(year) ? 366 : 365);
while (days > daysThisYear) {
days -= daysThisYear;
year += 1;
daysThisYear = (IsLeapYear(year) ? 366 : 365);
}
|
This compliant solution is for illustrative purposes and is not necessarily the solution implemented by Microsoft.
Risk Assessment
Failing to account for all possibilities within a logic statement can lead to a corrupted running state, potentially resulting in unintentional information disclosure or abnormal termination.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC01-C | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| missing-else switch-default | Partially checked | ||||||
Compass/ROSE | Can detect some violations of this recommendation. In particular, it flags switch statements that do not have a default clause. ROSE should detect "fake switches" as well (that is, a chain of if (x > 0) {
/* ... */
} else if (x < 0) {
/* ... */
} else if (x == 0) {
/* ... */
}
| ||||||||
GCC |
| Can detect some violations of this recommendation when the | |||||||
Helix QAC |
| C2000, C2002, C2004 | |||||||
Klocwork |
| CWARN.EMPTY.LABEL | |||||||
LDRA tool suite |
| 48 S, 59 S | Fully implemented | ||||||
Parasoft C/C++test |
| CERT_C-MSC01-a | All 'if...else-if' constructs shall be terminated with an 'else' clause The final clause of a switch statement shall be the default clause | ||||||
PC-lint Plus |
| 474, 744, 787, 9013 | Partially supported | ||||||
Polyspace Bug Finder |
| Checks for missing case for switch condition (rule partially covered) | |||||||
PVS-Studio |
| V517, V533, V534, V535, V556, V577, V590, V612, V695, V696, V719, V722, V747, V785, V786 | |||||||
RuleChecker |
| missing-else switch-default | Partially checked | ||||||
SonarQube C/C++ Plugin |
|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | VOID MSC01-CPP. Strive for logical completeness |
CERT Oracle Secure Coding Standard for Java | MSC57-J. Strive for logical completeness |
ISO/IEC TS 17961 | Use of an implied default in a switch statement [swtchdflt] |
ISO/IEC TR 24772 | Switch Statements and Static Analysis [CLL] |
Bibliography
[Hatton 1995] | Section 2.7.2, "Errors of Omission and Addition" |
[Viega 2005] | Section 5.2.17, "Failure to Account for Default Case in Switch" |
[Zadegan 2009] | "A Lesson on Infinite Loops" |
...
Hatton 95 Section 2.7.2 Errors of omission and addition