I came across the following C puzzle:
Q: Why does the following program segfault on IA-64, but work fine on IA-32?
int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = 10;
return 0;
}
I know that the size of int on a 64 bit machine may not be the same as the size of a pointer (int could be 32 bits and pointer could be 64 bits). But I am not sure how this relates to the above program.
Any ideas?
The cast to
int*masks the fact that without the proper#includethe return type ofmallocis assumed to beint. IA-64 happens to havesizeof(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
mallocis never needed and potentially bad.