...
In this example, the strlen()
function is used to limit the number of times the function string_loop()
will iterate. However, the programmer mistakenly subtracts 1
from the result of strlen()
. As a result, the last character before the terminating null character will never be processedThe conditional statement inside the loop is activated 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 string_loop(char *str) { size_t i; for (i=0; i < strlen(str)-1; i++) { /* Process str * ... */ if (str[i] == '\0') /* This code is never reached */ } return 0; } |
Compliant Solution 2
In this case, removing the dead code requires us to adjust the terminating condition of the loop so that every element in str
is processed. This can be done by not subtracting 1
from the result of strlen()
.
...