Code that is never executed is known as dead code. Typically, the presence of dead code indicates that a logic error has occurred as a result of changes to a program or the program's environment. Dead code is usually optimized out of a program during compilation. However, to improve readability and ensure that logic errors are resolved, dead code should be identified, understood, and eliminated.
This recommendation is related to guideline MSC12-C. Detect and remove code that has no effect.
Noncompliant Code Example
This noncompliant code example demonstrates how dead code can be introduced into a program [Fortify 2006]. The second conditional statement, if (s)
, will never evaluate true because it requires that s
not be assigned NULL
, and the only path where s
can be assigned a non-NULL
value ends with a return statement.
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle Error */ } /* Process s */ return 0; } /* ... */ if (s) { /* This code is never reached */ } return 0; }
Compliant Solution
Remediation of dead code requires the programmer to determine why the code is never executed and then to resolve the situation appropriately. To correct the preceding noncompliant code, the return
is removed from the body of the first conditional statement.
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle error */ } /* Process s */ } /* ... */ if (s) { /* This code is now reachable */ } return 0; }
Noncompliant Code Example
In this example, the strlen()
function is used to limit the number of times the function string_loop()
will iterate. The conditional statement inside the loop evaluates to true when the current character in the string is the null terminator. However, because strlen()
returns the number of characters that precede the null terminator, the conditional statement never evaluates true.
int string_loop(char *str) { size_t i; size_t len = strlen(str); for (i=0; i < len; i++) { /* ... */ if (str[i] == '\0') /* This code is never reached */ } return 0; }
Compliant Solution
Removing the dead code depends on the intent of the programmer. Assuming the intent is to flag and process the last character before the null terminator, the conditional is adjusted to correctly determine if the i
refers to the index of the last character before the null terminator.
int string_loop(char *str) { size_t i; size_t len = strlen(str); for (i=0; i < len; i++) { /* ... */ if (str[i+1] == '\0') /* This code is now reached */ } return 0; }
Exceptions
MSC07-EX1: In some situations, seemingly dead code may make software resilient. An example is the default
label in a switch
statement whose controlling expression has an enumerated type and that specifies labels for all enumerations of the type. (See recommendation MSC01-C. Strive for logical completeness.) Since 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.
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"; /* not dead code */ } } void g() { Color unknown = (Color)123; puts(f(unknown)); }
MSC07-EX2: It is also permissible to temporarily remove code that may be needed later. (See recommendation MSC04-C. Use comments consistently and in a readable fashion for an illustration.)
Risk Assessment
The presence of dead code may indicate logic errors that can lead to unintended program behavior. The ways in which dead code can be introduced into a program and the effort required to remove it can be complex. As a result, resolving dead code can be an in-depth process requiring significant analysis.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC07-C |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
Tool |
Version |
Checker |
Description |
---|---|---|---|
9.7.1 | 1 J |
Fully Implemented |
|
Splint |
3.1.1 |
|
can detect violations of this recommendation when the |
GCC |
4.3.5 |
|
can detect violations of this recommendation when the |
2024.3 | LV_UNUSED.GEN VA_UNUSED.* UNREACH.* |
|
|
2017.07 | DEADCODE |
can detect the specific instance where Code can never be reached because of a logical contradiction or a dead 'default' in switch statement |
|
2017.07 | UNREACHABLE |
can detect the instances where Code block is unreachable because of the syntactic structure of the code |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: MSC07-CPP. Detect and remove dead code
ISO/IEC TR 24772 "BRS Leveraging human experience," "BVQ Unspecified Functionality," and "XYQ Dead and Deactivated Code"
MISRA Rule 2.4
MITRE CWE: CWE-561, "Dead Code"
Bibliography
[Fortify 2006] Code Quality, "Dead Code"
MSC06-C. Be aware of compiler optimization when dealing with sensitive data 49. Miscellaneous (MSC) MSC09-C. Character Encoding - Use Subset of ASCII for Safety