...
In this example, the strlen()
function is used to limit the number of times the function strings_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.
Code Block |
---|
|
int strings_loop(char *strs) {
size_t i;
size_t len = strlen(strs);
for (i=0; i < len; i++) {
/* ... */
if (strs[i] == '\0') {
/* This code is never reached */
}
}
return 0;
}
|
Compliant Solution
...
Code Block |
---|
|
int strings_loop(char *strs) {
size_t i;
size_t len = strlen(strs);
for (i=0; i < len; i++) {
/* ... */
if (strs[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
MSC01-C. Strive for logical completeness.) Because valid values of an enumerated type include all those of its underlying integer type, unless enumeration constants are provided for all those values, the
default
label is appropriate and necessary.
...
...