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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With