为什么这段代码在 64 位架构上会出现段错误,但在 32 位上却能正常工作? [英] Why does this code segfault on 64-bit architecture but work fine on 32-bit?

查看:24
本文介绍了为什么这段代码在 64 位架构上会出现段错误,但在 32 位上却能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下 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;
  }

我知道在 64 位机器上 int 的大小可能与指针的大小不同(int 可以是 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) 这使得这个问题很明显.

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)

comp.lang.c FAQ 有一个条目讨论了 为什么从 malloc 转换返回是永远不需要的,而且可能很糟糕.

The comp.lang.c FAQ has an entry discussing why casting the return from malloc is never needed and potentially bad.

这篇关于为什么这段代码在 64 位架构上会出现段错误,但在 32 位上却能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆