Invariant expression in a condition, which causes unreachable code

The INVARIANT_CONDITION.UNREACH checker searches for true/false conditions in selection or iteration statements that cause unreachable code issues in their branches. This differs from unreachable code checkers, such as UNREACH.GEN or UNREACH.RETURN which report the unreachable code itself regardless of what caused it. The INVARIANT_CONDITION.UNREACH checker reports only the condition which caused an unreachable code. Since these checkers detect similar issues (though in a slightly different way) it makes sense to turn on INVARIANT_CONDITION.UNREACH only when unreachable code checkers are turned off.

Vulnerability and risk

Invariant conditions can cause unintended program behavior due to a mismatch between the code as written and the intended design. Invariant conditions can also cause confusion during code maintenance or code review.

Code example

   enum status_codes {
       ST_UNKNOWN = -1,
   extern void report_warn();
  extern void report_err();
  void report_status(int code)
      if (code < 0) {
      if (code >= ST_FATAL) {
      } else {
          if (code == ST_UNKNOWN) {  //   <== invariant condition
              exit(2);               // ( <== unreachable code )

Klocwork reports the 'code == ST_UNKNOWN' condition at line 22 as an INVARIANT_CONDITION.UNREACH issue, since the value of the variable 'code' is guarded by a non-negative value at this path by a previous check at line 15. The code branch controlled by this condition at line 13 is unreachable.

To fix this issue, change the order in which the conditions are checked.

Security training

Application security training materials provided by Secure Code Warrior.