Why does this code segfault on 64-bit architecture but work fine on 32-bit?

The cast to int* masks the fact that without the proper #include the return type of malloc is assumed to be int. IA-64 happens to have sizeof(int) < sizeof(int*) which makes this problem obvious.

(Note also that because of the undefined behaviour it could still fail even on a platform where sizeof(int)==sizeof(int*) holds true, for example if the calling convention used different registers for returning pointers than integers)

The comp.lang.c FAQ has an entry discussing why casting the return from malloc is never needed and potentially bad.

Leave a Comment