先看这道题,是国外一个人出的,大家分析下可能是什么原因?
IA-64下面的C程序错误,在IA-32正常,在IA-64上会出现段错误,为什么?
int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = 10;
return 0;
}
分析:
既然出现了段错误,那么肯定是涉及到了内存分配的因素。
对于32和64两种的区别:http://www.cnblogs.com/lovevivi/p/3334369.html
32位编译器:
char :1个字节
char*(即指针变量): 4个字节(32位的寻址空间是2^32, 即32个bit,也就是4个字节。同理64位编译器)
short int : 2个字节
int: 4个字节
unsigned int : 4个字节
float: 4个字节
double: 8个字节
long: 4个字节
long long: 8个字节
unsigned long: 4个字节
64位编译器:
char :1个字节
char*(即指针变量): 8个字节
short int : 2个字节
int: 4个字节
unsigned int : 4个字节
float: 4个字节
double: 8个字节
long: 8个字节
long long: 8个字节
unsigned long: 8个字节
重点是:int类型和指针变量已经不能匹配,所以会出错。
一篇国外文章可以借鉴下:http://stackoverflow.com/questions/5387090/segfault-on-ia-64-but-not-on-ia-32
On 32 bit implementations sizeof(int)
and sizeof(void*)
is 32 bits each. On 64 bit implementations sizeof(int)
is still the same but sizeof(void*)
is 64 bits.
Trucation of 64 bits pointer to 32 bits might be causing that problem.
Include <stdlib.h>
to solve the problem.
至于为什么加上<stdlib.h>头文件就会解决,这个我不明白,希望知道的朋友指点一二。