NUM.OVERFLOW.DF

Possible numeric overflow or wraparound

The NUM.OVERFLOW.DF checker detects possible cases of numeric overflow or wraparound in an arithmetic operation.

Vulnerability and risk

A numeric overflow condition can give results that lead to undefined behavior. In addition, an overflow can compromise the reliability and security of the program.

Vulnerable code example 1

Copy
  #include <stdio.h>
  void f()
  {
      unsigned short unA, unB;
      unsigned short unRet = 0;
  
      unA = 40000;
      unB = 30000;
      unRet = unA + unB;
  }

In the above example, Klocwork reports a NUM.OVERFLOW.DF defect at line 9 because the result of the arithmetic operation (addition) exceeds the range for ‘unsigned short’ on a platform that uses 16 bit for unsigned short.

Fixed code example 1

Copy
  typedef unsigned long long uint64_t;
  typedef unsigned int uint32_t;
  uint64_t foo(uint32_t x, uint32_t y) {
    uint64_t z;
    z = (uint64_t) ( x ) * y;
    z = (uint64_t) ( y ) * 1000000U; //or: y*1000000ULL
    return z;
  }

The compliant solution ensures that the addition operation never overflows by checking whether it will exceed the range before the arithmetic operation is performed.

Vulnerable code example 2

Copy
 #include <stdio.h>
 void g()
 {
     signed int lX, lY;
     unsigned long long llZ = 0;
     lX = 2000000000;
     lY = 2000000000;
     llZ = (unsigned long long)(lX * lY);
 }

In this example, Klocwork reports a NUM.OVERFLOW.DF defect at line 8 on a platform in which ‘signed int’ is 32 bit or less because multiplication will first be executed in 32 bit (‘signed int’) which causes the overflow before it is followed by a cast to 'unsigned long long'.

Fixed code example 2

Copy
 #include <stdio.h>
 void g()
 {
     signed int lX, lY;
     unsigned long long llZ = 0;
     lX = 2000000000;
     lY = 2000000000;
     llZ = (unsigned long long) (lX) * lY;
 }

In the compliant example above, the variable ‘lX’ was up cast first, which causes ‘lY’ to be promoted automatically, leading to the multiplication being performed on ‘unsigned long long’ (64 bit) which does not result in an overflow.

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.

Extension

This checker cannot be extended.