C/C++ Programmer's Guide (G06.25+)

Handling TNS Data Alignment
HP C/C++ Programmer’s Guide for NonStop Systems429301-008
23-5
C/C++ Misalignment Examples
and the system configuration, but they might include erratic “rounding down” and
abnormal program termination.
In a TNS-compiled C or C++ program, some actions that can cause misaligned
addresses are:
1. Using a null or uninitialized pointer
When a structure pointer is null or uninitialized, the structure’s fields are random
bits, which could give a random misaligned address if a pointer field is
dereferenced. Examples:
a. Dereferencing a pointer-valued field of a structure when the structure pointer is
null
b. Checking for a null pointer after some but not all pointer references, instead of
before all pointer references (see Example 23-1 on page 23-7).
c. Dereferencing a pointer-valued member of a union when that alternative is not
active and initialized
2. Using syntactically correct but semantically incorrect and nonportable casts of the
following kinds:
To an integer pointer
To a structure pointer
From a char * pointer
From a void * pointer
From an integer expression
(For information about writing portable programs, see Writing Portable Programs
on page 1-19.)
These casts work only in TNS programs when the converted address is correctly
aligned for integer or structure objects (that is, when it is an even-byte address).
The following are correctly aligned (that is, they have even-byte addresses):
Compiler-allocated objects
Heap objects
The following might be misaligned (that is, they might have odd-byte addresses):
Declared items
°
char strings
°
Elements of char arrays
°
char fields of structures
Calculated items
°
char subscripts
°
Incremented char or void pointers
°
Casts of odd-valued integer expressions into a pointer types