(Raju) writes:
[...]
> I am little confused about the explanation.
> I think size of "int" is size of processor register length.
> And malloc retuns 64 bit address and pointer is also 64 bit (whether
> int * or char *) , then where actually the size giving problem.
The size of "int" is whatever the compiler implementer decides it
should be. On the IA-64 (also known as Itanium), int is 32 bits, and
pointers are 64 bits. More precisely, these are the sizes chosen by
the compilers I'm familiar with on IA-64 systems (gcc and Intel's
compiler under Linux). Note that there's a strong motivation for
different compilers on the same system to be compatible with each
other.
Since the IA-64 is a 64-bit system, it's natural to assume that int
should be 64 bits, but that would actually cause some problems.
Currently, the types of the predefined integer types are:
char 8 bits
short 16 bits
int 32 bits
long 64 bits
long long 64 bits
If int were 64 bits, short would be either 16 or 32 bits, leaving a
gap in the type system. (C99 allows extended integer types, with
appropriate typedefs in <stdint.h>, but portable code can't yet depend
on this.)
> And can i know how the code below behaves on both platforms,
>
> int main()
> {
> char* p;
> p = (char*)malloc(sizeof(char));
> *p = 10;
> return 0;
> }
With the understanding that it's undefined behavior regardless
of the underlying system:
On IA-32: no ouput.
On IA-64: Segmentation fault.
Here's another program that shows more clearly what's going on:
#ifdef INCLUDE_STDLIB
#include <stdlib.h>
#endif
#include <stdio.h>
int main()
{
char* p;
p = (char*)malloc(sizeof(char));
printf("p = %p\n", p);
fflush(stdout);
*p = 10;
return 0;
}
On IA-32, this produces nearly the same output whether INCLUDE_STDLIB
is defined or not:
p = 0x8648008
(The specific address changes for some irrelevant reason.)
On IA-64, if INCLUDE_STDLIB is not defined, the output is:
p = 0xc80
Segmentation fault
If INCLUDE_STDLIB is defined, the output is:
p = 0x6000000000000c80
Of course none if this arises if you just write the code properly in
the first place: use a "#include <stdlib.h>" directive, and don't cast
the result of malloc().
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.