Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

puzzle

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?

like image 564
whacko__Cracko Avatar asked Mar 22 '11 05:03

whacko__Cracko


2 Answers

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).

like image 183
ChrisWue Avatar answered Sep 20 '22 13:09

ChrisWue


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.

like image 24
Prasoon Saurav Avatar answered Sep 19 '22 13:09

Prasoon Saurav