*** Welcome to piglix ***

Unreachable code


In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.

Unreachable code is sometimes also called dead code, although dead code may also refer to code that is executed but has no effect on the output of a program.

Unreachable code is generally considered undesirable for a number of reasons, including:

The existence of unreachable code can be due to various factors, such as:

In the latter five cases, code which is currently unreachable is often there as part of a legacy, i.e. code that was once useful but is no longer used or required. However, the unreachable code may also be part of a complex component (library, module or routine), where the code continues to be useful in conjunction with different input data (never generated by the current application) or under conditions which are not met in the current runtime environment, thereby making the corresponding code unreachable, but which can occur in other runtime environments, for which the component has been developed.

An example of such a conditionally unreachable code may be the implementation of a printf() function in a compiler's runtime library, which contains complex code to process all possible string arguments, of which only a small subset is actually used in the program. Without recompiling the runtime library, compilers will typically not be able to remove the unused code sections at compile time.

Consider the following fragment of C code:

The definition int Z = X * Y; is never reached as the function returns before the definition is reached. Therefore, the definition of Z can be discarded.

An example of real life code that contained a major security flaw due to unreachable code is Apple's SSL/TLS bug formally known as CVE-2014-1266 and informally known as the "goto fail bug" from February 2014. The relevant code fragment is listed below:

Here, there are two successive calls to goto fail. In the syntax of the C language, the second one is unconditional, and hence always skips the call to the final check. As a consequence, err will contain a successful value after the SHA1 update operation was successful, and the signature verification will never declare a failure, as the final check is omitted.

Here, the unreachable code is the call to the final function, which should have been reached. There are several good coding practices that could have prevented this fault from occurring, such as code reviews, the proper use of indentation or curly braces, and test coverage analysis. Applying the Clang compiler with the option -Weverything includes unreachable code analysis, which would trigger an alarm for this code.


...
Wikipedia

...