UNREACH.GEN

Unreachable code

The UNREACH.GEN checker looks for unreachable statements in the code-any code that will never be executed. Usually the result of a logic error, unreachable code is often caused by life-cycle changes to a program or its expected runtime environment.

Vulnerability and risk

Unreachable code can cause unintended program behavior due to a mismatch between the code as written and the intended design. Dead code can also cause confusion during code maintenance or code review. In certain edge cases, the presence of unreachable code can lead to code vulnerabilities when that dead code is responsible for guarding specific resources or code branches.

Recommendations for fixing code flagged with an instance of UNREACH.GEN are hard to make, since the code may be unreachable because of an error, or simply because the developer wanted to write code as safely as possible and added extra code that in real life is unreachable.

Vulnerable code example 1

Copy
    extern void exit(int);
    int stub();

    int demo_return_or_exit(int t) {
        if (t > 0) {
            return t + 1;
        } else {
            exit(22);
        }
       stub(); 
       return t + 3;
    }

In this example, Klocwork produces an unreachable code report to indicate that the call to the 'stub()' function in line 10 is unreachable. All the paths of the preceding if/else statement terminate the function. If the unreachable code is redundant, it can safely be removed. Alternatively, if any of the preceding terminating statements is misplaced, it can be removed or put into a conditional statement.

Vulnerable code example 2

Copy
    extern void exit(int);
    int stub();
    
    int demo_infeasible_if(int t) {
        if (t > 0) {
            if (t == 0) {
                stub(); // <== unreachable
            }
        }
       return t - 1;
    }

In this case, Klocwork produces an unreachable code report to indicate that the call to the 'stub()' function in line 7 is unreachable, because it occurs on a path in which the conditions aren't feasible-'t' can never be equal to 0 on a path on which it's greater than 0. To fix the problem, the infeasible check and subsequent unreachable code can be removed if they're redundant. Alternatively, any incorrect path conditions can be changed.

Related checkers

Extension

This checker can be extended. See Tuning C/C++ analysis for more information.