UNREACH.SIZEOF

Unreachable code due to a condition on 'sizeof'

The UNREACH.SIZEOF checker looks for code that will never be executed because it is guarded by a condition on the size of a data type (calculated by the ‘sizeof’ keyword) that is always false on the targeted architecture when compiling the code. A typical use for UNREACH.SIZEOF is to separate unreachable code due to a condition on architecture dependent ‘sizeof’ from other types of unreachable code. It is useful to be able to turn off the UNREACH.SIZEOF checker when it is expected that there will be unreachable code that is dependent on the size of the data types used, but you still want to check for more generally unreachable code with UNREACH.GEN.

Vulnerability and risk

Unreachable code due to a condition on ‘sizeof’ can cause confusion during code maintenance and/or code review.

Vulnerable code example

1 int get_ptr_size(void* ptr)
2 {
3   int x = 0;
4   switch (sizeof(ptr)) {
5   case 4:
6     x = 4;
7     break;
8   case 8:
9     x = 8;
10    break;
11  default:
12    x = 16;
13    break;
14  }
15  return x;
16 }

Klocwork produces a report of unreachable code, indicating that some cases are never reached. The cases reported will vary by the targeted architecture. For example, if the size of a pointer in the targeted architecture is 32 bits (4 bytes), then the case 4 is the only case reachable. Then, defect will be reported for the case 8 (line 9). Obviously in this scenario, the behavior is benign and would typically cause the reviewer to turn this checker off (particularly if the code is intended to be compiled for different architectures).

Related checkers

Extension

This checker cannot be extended.