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

Handling TNS Data Alignment
HP C/C++ Programmer’s Guide for NonStop Systems429301-008
23-6
C/C++ Misalignment Examples
See:
Example 23-2 on page 23-8
Example 23-3 on page 23-8
Example 23-7 on page 23-9
3. Using a pointer union without direct assignment
Union of a pointer with other pointers or with integers is safe when the values of
the unions are mutually exclusive in time or when an equivalent explicit assignment
of the address value would be correct at run time. See Example 23-4 on
page 23-8.
4. Calling an undeclared or misdeclared external function
Actual parameter values are implicitly assigned to formal parameters. If formal
parameters are described incorrectly, these implicit assignments are equivalent to
unchecked type casts.
5. Using an explicit number for the offset of a structure field or for the size of a
structure
This practice can cause misaligned addresses by overlooking the implicit filler
bytes that the TNS compiler adds to structures as follows:
Within structures, to ensure that every noncharacter field begins at an even-
byte offset from the beginning of the structure
At the end of any structure that contains some noncharacter fields and has an
odd number of bytes, to give it an even number of bytes
See Example 23-5 on page 23-8.
To prevent this problem, use an offsetof() macro to get the offset of a structure
field and the sizeof instruction to get the size of a structure.
6. Customizing the heap allocation method
If a TNS program implements its own customized heap allocation method, it must
ensure that all objects except char objects are aligned and allocated on even-byte
boundaries.
7. Appending a sequence of objects into a string buffer or char array
If a TNS program appends a sequence of objects into a string buffer or a char
array, it must ensure that nonstring objects are aligned and allocated on even-byte
boundaries.
8. Addressing an external data item that contains misaligned parts (as short or
larger items)
If a TNS program uses external data items (files or structures) that have
misaligned parts (such as those on computer systems that have no data alignment
requirements), it must declare and directly access them as char arrays rather than
as short or larger items. See Example 23-6 on page 23-9.