Array alignment on HPUX

Hi,

I'm porting code from Windows to HP-UX 11.23, using gcc (I'm begining to suspect this might not be the best choice, but I thought it would be most compatible since we've already compiled on Linux with gcc).

I have in my code something similar to the folowing:

unsigned char *ch_arr = new (unsigned char)[20];
unsigned char ptr = ch_arr + 10;
unsigned int number = 100;

*((unsigned int *)ptr - 1) = number;

The last line gives a segmentation fault.
In fact, I have found that its enough to write the following in order to crash:

unsigned char *ch_arr = new (unsigned char)[20];
unsigned int number = 100;

ch_arr[2] = number;

And the same is true for any index in the array which does not divide by 4.
I assume this is an alignment problem. If I were writing new code I could work around it, but since I am porting code this is a problem. Apparently the code uses this type of code, treating char arrays as memory buffers for different types, in many places and it would be very difficult to find them all and fix them.

Is there any compilation flag that could change the alignment for me?
Any other ideas for a global fix for this?

Thanks!

RO

Excellent problem!

You will find yourself in a bit of a pickle unless you sort out the misaligned accesses.

If you use structures then the compiler will automatically insert the correct padding to provide the type alignment.

Here are a couple of useful macros

#define offsetof(x,y)	((long)((char *)&(((x *)0)->y)))
#define alignof(x)	(short)(long)(&((struct { char _x; x _d; } *)NULL)->_d)

I am beginning to appreciate my pickled situation...

I'm intrigued about the macros. I understand that in 'alignof' x is a type, correct?
I tried it but my compiler says:

error: types may not be defined in casts

Yes a type. It will work for a basic types and typedef'd types.

Which compiler are you using? I'm a bit concerned... :slight_smile:

I've used HP's PA-RISC compiler, it's Itanium2, gcc and they are all happy with it.

I've found it to be highly portable, and I mean gcc, MIPSpro, HP's cc, Sun's cc, Visual C++, Tru64's cc.

First of all the line of code I wrote is:

        fprintf( stderr, "alignof : %d\n", alignof(UINT) );

Where UINT is defined as 'unsigned int'. This gives me the compilation error I mentioned.
I'm using gcc 4.2.1 on HPUX on Itanium: ia64-hp-hpux11.23