您的位置:首页 > 编程语言 > C语言/C++

C/C++日常学习总结(第十六篇)分析IA-64和IA-32位机器上同一个程序运行,前者报错,后者正常

2014-08-15 13:04 525 查看
先看这道题,是国外一个人出的,大家分析下可能是什么原因?

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>头文件就会解决,这个我不明白,希望知道的朋友指点一二。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐