Library tutorials & articles

Typical errors of porting C++ code on the 64-bit platform

Implicit type conversions while using functions

Observing the previous kind of errors related to mixing of simple integer types and memsize types, we surveyed only simple expressions. But similar problems may occur while using other C++ constructions too.

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

In case if you work with large arrays (more than INT_MAX items) the given code may behave incorrectly and we’ll address not those items of the array MyArray we wanted. In spite the fact that we return the value of size_t type "x + y * Width + z * Width * Height" expression is calculated with the use of int type. We suppose you have already guessed that the corrected code will look as follows:

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);
}

In the next example we also have memsize type (pointer) and simple unsigned type mixed.

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

The result of "end - begin" expression have ptrdiff_t type. As far as the function returns unsigned type the implicit type conversion occurs during which high bits of the results get lost. Thus if pointers begin and end address the beginning and the end of the array according to the larger UINT_MAX (4Gb), the function will return the incorrect value.

And here it is one more example but now we’ll observe not the returned value but the formal function argument.

void foo(ptrdiff_t delta);

int i = -2;
unsigned k = 1;
foo(i + k);

Does not this code remind you of the example of the incorrect pointer arithmetic discussed earlier? Yes, we find the same situation here. The incorrect result appears during the implicit type conversion of the actual argument which has value 0xFFFFFFFF and from unsigned type to ptrdiff_t type.

Comments

  1. 01 Jan 1999 at 00:00

Leave a comment

Sign in or Join us (it's free).

Andrey Karpov
AddThis

Related podcasts

  • Interview with Shawn Burke on Microsoft's .NET Source Code Release

    Scott and Carl talk with Shawn Burke on the culmination of his many-year-old plan to get parts of the source of the .NET Framework released. With Visual Studio 2008, a simple process will allow developers to STEP INTO the .NET Framework Source from the IDE. This'll be a great debugging and learni...

We'd love to hear what you think! Submit ideas or give us feedback