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.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The trouble with programmers is that you can never tell what a programmer is doing until it's too late.” - Seymour Cray