HP C Programmer's Guide (92434-90009)

30 Chapter2
Storage and Alignment Comparisons
The HP_ALIGN Pragma
.
.
.
}
}
This code is not written safely. Although struct s is declared under NOPADDING alignment
mode, it has 2-byte alignment due to the typedef for ushort. However, a pointer to struct
s can be assigned an address that can point to anywhere in the char array (including odd
addresses). If the function get_index always returns an even number, you will not run
into any problems, because it will always be 2-byte aligned. However, if the index happens
to be an odd number, &myBuffer[index] will be an odd address. Dereferencing that
pointer to store into a 2-byte aligned member will result in a run-time bus error.
Below are some examples of what you can do to avoid such behavior.
Compile with +u1 option, which forces all pointer dereferences to assume that data is
aligned on 1-byte boundaries. However, this will have a negative impact on
performance.
Put the typedef inside the NOPADDING alignment. However, if you use ushort in
contexts where it must have 2-byte alignment, this may not be what you want.
Declare struct s with the basic type unsigned short rather than the typedef ushort.
Make sure that the pointer will always be 2-byte aligned by returning an even index
into the char array.
Declare another typedef for ushort under the NOPADDING alignment:
typedef ushort ushort_1
and use the new type ushort_1 inside struct s.
As mentioned above, the HP_ALIGN pragma must have a global scope; it must be outside of
any function or enclosing structure or union. For example, suppose you have the following
sequence of pragmas:
#pragma HP_ALIGN HPUX_WORD PUSH
struct string_1 {
char *c_string;
int counter;
};
#pragma HP_ALIGN HPUX_NATURAL PUSH
struct car {
long double car_speed;
char *car_type;
};
#pragma HP_ALIGN POP
struct bus {
int bus_number;