Viva64 Send comments on this topic.
V109. Implicit type conversion of return value to memsize type

Glossary Item Box

The analyzer found a possible error related to the implicit conversion of the return value type. The error may consist in the incorrect determination of the return value.

Let’s examine an example.

  CopyCode image Copy Code
extern int Width, Height, Depth;
size_t GetIndex(int x, int y, int z) {
  return x + y * Width + z * Width * Height;
}
...
array[GetIndex(x, y, z)] = 0.0f;

If the code deals with large arrays (more than INT_MAX items) it will behave incorrectly and we will address not those items of the array array that we want. But the analyzer won’t show a warning message on the line array[GetIndex(x, y, z)] = 0.0f; for it is absolutely correct. The analyzer informs about a possible error inside the function and is right for the error is located exactly there and is related to the arithmetic overflow. In spite of the facte that we return the type size_t value the expression x + y * Width + z * Width * Height is determined with the use of type int.

To correct the error we should use the explicit conversion of all the variables included into the expression to memsize types.

  CopyCode image Copy Code
extern int Width, Height, Depth;
size_t GetIndex(int x, int y, int z) {
  return (size_t)(x) +
      (size_t)(y) * (size_t)(Width) +
      (size_t)(z) * (size_t)(Width) * (size_t)(Height);
}

Another variant of correction is the use of other types for the variables included into the expression.

  CopyCode image Copy Code
extern size_t Width, Height, Depth;
size_t GetIndex(size_t x, size_t y, size_t z) {
  return x + y * Width + z * Width * Height;
}

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 in this line. For example:

  CopyCode image Copy Code
DWORD_PTR Calc(unsigned a) {
  return (DWORD_PTR)(10 * a);
}

In case you suspect that the code contains incorrect explicit type conversions to memsize types about which the analyzer does not show warnings you may use the Find incorrect explicit type conversion mode.

See also:

memsize type

limitations of the analyzer Viva64

implicit type conversion

explicit type conversion

how to find the explicit type conversion