|
Home > Archive > Unix Programming > June 2004 > HPUX compiler - code snippet - passing pointers to function
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
HPUX compiler - code snippet - passing pointers to function
|
|
|
| Hi,
Could someone tell me what is wrong with doing the following.
ON HPUX (fine on Linux, sco, aix), it bus errors when func references *n
void main(argc,argv)
int argc;
char* argv[];
{
extern int func();
short *ptr; /* NOTE short */
ptr = (short *) malloc(12);
(void) func( (ptr+1) );
}
int func(n)
int *n; /* If I change this to short -or the above short to int, it's fine */
{
return *n;
}
Regards,
Ian.
| |
| Sean Burke 2004-06-20, 10:32 pm |
|
ianc@kiwiplan.co.nz (Ian) writes:
> Hi,
> Could someone tell me what is wrong with doing the following.
> ON HPUX (fine on Linux, sco, aix), it bus errors when func references *n
>
> void main(argc,argv)
> int argc;
> char* argv[];
> {
> extern int func();
> short *ptr; /* NOTE short */
>
> ptr = (short *) malloc(12);
>
> (void) func( (ptr+1) );
> }
>
> int func(n)
> int *n; /* If I change this to short -or the above short to int, it's fine */
> {
> return *n;
> }
Couple of things going on here: data alignment, and pointer
arithmetic.
The value (ptr+1) that you are passing to func is not aligned
properly. For some processors like Sparc and PA-Risc, there
are alignment constraints on data - short integers need to be
at even addresses, 32-bit ints need to be at an address that
is a multiple of four, etc. The convention is to raise SIGBUS
when a load or store has a mis-aligned address.
The malloc() call will always return a pointer that is aligned
to the largest boundary you might need (typically a multiple of
8 bytes, to accomodate doubles, which contributes to heap
fragmentation BTW).
Pointer arithmetic comes in when (ptr+1) is evaluated, because
the resulting address depends on the data type of ptr. If ptr
is defined as a short, then ptr+1 equals ptr plus two bytes,
yielding a badly aligned address for an int. If ptr is of int
type, then (ptr+1) is equal to ptr plus four bytes, which is
properly aligned for either short or int.
Hope this helps.
-SEan
|
|
|
|
|