问题描述
以下C程序在64位Arch。上有段错误,但在32位/ b $ b位上工作正常。
int main()
{
int * p;
p =(int *)malloc(sizeof(int));
* p = 10;
返回0;
}
为什么会这样?
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.
int main()
{
int* p;
p = (int*)malloc(sizeof(int));
*p = 10;
return 0;
}
Why does it happen so?
推荐答案
-
"如果你以后会成为真正的寻求者事实上,你生命中至少有一次你必须尽可能地怀疑所有的事情。
- Rene Descartes
--
"If you would be a real seeker after truth, it is necessary that at
least once in your life you doubt, as far as possible, all things."
-- Rene Descartes
这会崩溃,因为:
1)你没有在malloc中包含正确的标题。
2)编译器认为它是一个未知函数返回
defau结果:一个整数。
3)编译器生成代码以从malloc
(32位整数)读取整数结果,然后将其转换为64位指针。一些
位的指针都会丢失。
4)因为你对(int *)进行了强制转换,编译器不会警告你
关于将一个整数转换为指针,因为它是明确的
要求。
5)你在指针中存储了错误的地址,当你使用它时
崩溃。
jacob
This will crash because:
1) You did not include the proper header to malloc.
2) The compiler assumes it is an unknown function that returns
the default result: an integer.
3) The compiler generates code to read an integer result from malloc
(32 bit integer) and then casts it to a 64 bit pointer. Some
bits of the pointer are lost.
4) Since you did a cast to (int *) the compiler will not warn you
about casting an integer to a pointer since it is explicitely
asked for.
5) You store the wrong address in the pointer and when you use it it
crashes.
jacob
这篇关于救命。错误是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!