Segfault on IA-64, but not on IA-32

2020-07-10 19:56发布

问题:

I can't access my original account. Moderators are requested to merge the accounts if possible.
Here is my question. The following C program segfaults of IA-64, but works fine on IA-32.

int main()
  {
      int* p;
      p = (int*)malloc(sizeof(int));
      *p = 10;
      return 0;
  }

Why does it happen so?

回答1:

In C the default return type is int if the function is not prototyped. In ia64 the size of a pointer is larger than an int and so it can segfault.

Update: The question is basically why you should always prototype your functions (or include the appropriate headers for that matter).



回答2:

One of the reasons I could think of is that the prototype of malloc is missing considering pre 99 compiler.

Implicit int (return type) is deprecated. However if your code segfaults that means the compiler assumes that functions (without any prototype in scope) return integer by default. As a result malloc would be treated as returning an integer instead of a pointer.

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.



回答3:

As it's IA64 (itanic) and not x64 it's probably something basic like malloc not guaranteeing alignment, cf. memalign and early versions of IA64 don't support unaligned memory access.



标签: c puzzle