问题描述
我碰到下面的C砌出来:
I came across the following C puzzle:
问:为什么在IA-64下面的程序段错误,但在IA-32正常工作
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;
}
我知道 INT
的大小在64位计算机上可能不一样的指针( INT $的大小C $ C>可能是32位,并且指针可以是64位)。但我不知道如何这涉及到上面的程序。
任何想法?
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?
推荐答案
演员到为int *
掩盖的事实,如果没有适当的的#include
的malloc的返回类型假设
是 INT
。 IA-64恰巧有的sizeof(int)的<的sizeof(INT *)
这使得这个问题明显。
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.
(另请注意,因为不确定的行为仍可能会失败,即使在一个平台上,其中的sizeof(int)的==的sizeof(INT *)
也是如此,例如如果调用约定使用不同的寄存器用于返回指针不是整数)
(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.
这篇关于为什么在64位架构,但做工精细此code段错误在32位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!