HP aC++/HP C A.06.28 Programmer's Guide Integrity servers (769150-001, March 2014)
NOTE: The alignment of specializations and partial specializations of templates is undefined
and unsupported if either the primary template or the specialization is under the influence of a
#pragma pack directive.
Handling Unaligned Data
Direct access to unaligned class fields is handled automatically by HP aC++. However, this results
in slower access times than for aligned data. Indirect access (through pointers and references) to
unaligned class fields is also handled automatically.
If you take the address of a data field and assign it to a pointer, it is not handled automatically
and is likely to result in premature termination of the program if not handled appropriately.
Example:
#include <stdio.h>
#pragma pack 1
struct S1 {
char c1;
int i;
char c2;
};
#pragma pack
int main() {
S1 s;
S1 *p = &s;
printf(“%d\n”, s.i); // OK
printf(“%d\n”, p->i); // OK
int *ip = &p->i; // Undefined behavior
// Likely Abort unless compiled with +u1
// The address of a reference (*ip) is
// assigned to an int pointer.
printf(“%d\n”, *ip);
}
To enable indirect access to unaligned data that has been assigned to another type, use the link
in the library, -lunalign and arm the appropriate signal handler with a call to
allow_unaligned_data_access. This causes every signal generated due to unaligned access
to be intercepted and handled as expected. It also creates significant run-time overhead for every
access to unaligned data, but does not impact access to aligned data.
Implicit Access to Unaligned Data
Calls to non-static member functions require that an implicit this pointer be passed to these
functions, which can then indirectly access data through this implicit parameter. If such an access
is to unaligned data, the situation in the prior example occurs.
Furthermore, virtual function calls often require indirect access to a hidden field of a class that
could be unaligned under the influence of the #pragma pack directive.
If you are passing the address of a field to other code, consider the following example. Unless
compiled with -DRECOVER on the command line and linked with -lunalign, the following
example is likely to prematurely terminate with a bus error:
#include <stdio.h>
#ifdef RECOVER
extern “C” void allow_unaligned_data_access();
#endif
#pragma pack 1
struct PS1 {
PS1();
~PS1();
private:
Data Alignment Pragmas 101