V110. Implicit type conversion of return value from memsize type to 32-bit type.


The analyzer found a possible error related to the implicit conversion of the return value. The error consists in dropping of the high bits in the 64-bit type which causes the loss of value.

Let's examine an example.

extern char *begin, *end;
unsigned GetSize() {
  return end - begin;
}

The result of the end - begin expression has type ptrdiff_t. But as the function returns type unsigned the implicit type conversion occurs which causes the loss of the result high bits. Thus, if the pointers begin and end refer to the beginning and the end of the array according to a larger UINT_MAX (4Gb), the function will return the incorrect value.

The correction consists in modifying the program in such a way so that the arrays sizes are kept and transported in memsize types. In this case the correct code of the GetSize function should look as follows:

extern char *begin, *end;
size_t  GetSize() {
  return end - begin;
}

In some cases the analyzer won't display a warning message on type conversion if it is obviously correct. For example, the analyzer won't display a warning message on the following code where despite the fact that sizeof() operator's result is size_t type it can be safely placed into unsigned type:

unsigned GetSize() {
  return sizeof(double);
}

When you are sure that the code is correct and the implicit type conversion does not cause errors while porting to the 64-bit architecture you may use the explicit type conversion so that to avoid showing of the warning messages. For example:

unsigned GetBitCount() {
  return static_cast<unsigned>(sizeof(TypeRGBA) * 8);
}

If you suspect that the code contains incorrect explicit conversions of the return values types about which the analyzer does not warn you may use the V202.

Additional materials on this topic:


Bugs Found

Checked Projects
344
Collected Errors
12 970