CWARN.NOEFFECT.OUTOFRANGE

Value outside of range

Ineffective binary comparison due to out of range literal constants.

The CWARN.NOEFFECT.OUTOFRANGE checker is limited to situations where the result of the operation on the left or right side of the binary operator fits the width of a signed 64-bit integer variable.

Vulnerability and risk

If, in binary comparisons where on one side there is an expression and on the other side there is a literal expression; and, the value of the literal expression is out of the permitted values by the expression; then, the comparison is ineffective. This kind of comparison can be either always true or always false depending on the context. In order to avoid such problems in code, you need to type-cast the expression properly or use the right literal expression for the case.

Vulnerable code example 1

Copy
 void foo(){
     unsigned char i;
     int a[256];
     for(i=0;i<256;i++) {
         a[i]=1;
     }
 }

In the above example the variable 'I' cannot hold a value bigger than 255; but it is being compared to the constant 256 and hence the comparison "i<256" is invariantly true. This will cause an infinite loop. Klocwork produces CWARN.NOEFFECT.OUTOFRANGE on line 4 alerting the developer for the problem.

Fixed code example 1

Copy
 void foo(){
     int i;
     int a[256];
     for(i=0;i<256;i++) {
         a[i]=1;
     }
 }

Once simple fix is depicted in the above example where the variable is declared as "int" instead of "unsigned char" and thus expanding the permitted range of values for the variable 'I'.

Vulnerable code example 2

Copy
 void foo(int x) {
     if (x*x != (0x7fff*0x7ffff)) {
     }
 }

A slightly more complex case is shown in the above example where both the expression and the literal expression have sub-expressions. But the literal expression evaluates to an integer that a 4-byte integer cannot hold. Klocwork produces a defect on line 2.

Fixed code example 2

Copy
 void foo(int x) {
     long long x_sqr = (long long)x*x;
     if (x_xqr != (0x7fff*0x7ffffLL)) {
     }
 }

The value of "x*x" was computed with proper type-casting along with the literal 0x7ffff which is prefixed with "LL"; leading to a full 64-bit comparison.

Related checkers