Friday, May 12, 2006

Compilation problems in 64 bit machines

Problem: (it happenned to me while compiling an MPI program, but it is independent of it)

You malloc() an array, print the address in a 64 bit machine, and oops, it segfaults.

Allocate an array:

one_malloc = malloc (3*(sizeof(double) * ( N ) + OFFSET + PAGE_SIZE));
printf("one_malloc=%lld\n", one_malloc);

And it prints:

one_malloc=5156880

mmmm... Looks more like a 32 bit integer, than a 64 bit long one.

The problem seems "malloc" is returning an integer. That is the case:

Have you included "malloc.h"?

In a 64 bit machine with pointers of 64 bits and integers of 32, leaving the prototypes behind will lead to all sort of problems and bugs, some of them very hard to spot. The reason: everything not having a prototype defaults to "int".

I still wonder why are there machines with this mixed 32 integers/64 pointers, which totally break pointer arithmetic of 32 programs, particularly when there isn't an specific type for pointer arithmetic, if there had been, it would be the fault of the programmers, but pointer arithmetic was always allowed.

Having a type u32, u64 fo this looks ugly to me, because the programmer must know beforehand the sizes of the different types. One could argue: but that's fixed for a machine. No. There are machines that support 32 and 64 bits, gcc and a native compiler and that have two different set of libraries (32 and 64 bits) compiled.

If now integer is not available for pointer arithmetic, what's left? long long is not guaranteed to be of the same length as a pointer.

How to solve this issue in a beautiful, portable, standard way? thanks!

0 comments: