Versions Compared

Key

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

...

Wiki Markup
This non-compliant code example demonstrates how dead code can be introduced into a program \[[Fortify 06|AA. C References#Fortify 06]\]. 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.

...

Code Block
bgColor#ccccff
int func(int condition) {
    char *s = NULL;
    if (condition) {
        s = (char *)malloc(10);
        if (s == NULL) {
           /* Handle Errorerror */
        }
        /* Process s */
    }
    /* ... */
    if (s) {
        /* This code is now reachable */
    }
    return 0;
}

...

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 null terminator. However, because strlen() returns the number of characters that precede the NULL null terminator, the conditional statement never evaluates true.

...

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 null terminator, the conditional is adjusted to correctly determine if the i refers to the index of the last character before the NULL null terminator.

Code Block
bgColor#ccccff
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;
}

...

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 in to 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.

...