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

Handling TNS Data Alignment
HP C/C++ Programmer’s Guide for NonStop Systems429301-008
23-8
C/C++ Misalignment Examples
Example 23-2. C/C++ Invalid Cast From char to Integer Pointer (Item 2, Item 10)
Change this:
/* extract 16-bit length from front of long string: */
unsigned char *name;
lth = * (unsigned short *) name; /* misalignment traps here */
name += 2;
To this:
/* extract 16-bit length from front of long string: */
unsigned char *name;
lth = (name[0] << 8) | name[1]
name += 2;
Example 23-3. C/C++ Invalid Cast From char to Integer Pointer
(Item 2, Item 10)
Change this:
/* insert 16-bit length at front of long string: */
unsigned char *name;
unsigned short lth;
* (unsigned short *) name = lth;
To this:
/* insert 16-bit length at front of long string: */
unsigned char *name;
unsigned short lth;
name[0] = lth >> 8;
name[1] = lth;
Example 23-4. C/C++ Pointer Union (Item 3, Item 10)
Change this:
/* type cast done via union: */
union { unsigned char *bytes;
unsigned short *shorts; } u;
u.bytes = name;
lth = * u.shorts; /* misalignment traps here */
To this:
lth = (name[0] << 8) | name[1];
Example 23-5. C/C++ Structure With Implicit Filler Bytes (Item 5)
struct elem {
char a; /* offset 0 */
/* implicit filler byte added before b */
short b; /* offset 2 */
char c; /* offset 4 */
/* implicit trailing filler byte added after c */
/* with filler bytes, total size is 6 bytes */
};
struct elem table[10]; /* each table element takes 6 bytes, not 4 */