3.2 Data Structures and Sizes

To be able to generate efficient code, compilers have to follow the byte alignment restrictions defined by the target processors. This means that compilers have to add pad bytes into user-defined structures so that the structure does not violate any restrictions imposed by the target processor. The compiler padding is illustrated in the following example. Here, an int is assumed to be 4 bytes, a short is 2 bytes, and a char is a single byte.

 struct mydata {
    char C;
    long L;
    short B;
    long J;
}; 

3.3 illustrates how struct mydata would be padded to align with 4-byte boundaries.

Figure 3.3 Memory Alignment and Padding of Structures

The diagram illustrates how memory is padded for struct mydata so that its members are correctly aligned. The char member C is represented as four bytes [C] [p] [p] [p], where [p] is a byte of padding. The long member L is represented as [L0] [L1] [L2] [L3]. The short member B is represented as [B0] [B1] [p] [p]. The long member J is represented as [J0] [J1] [J2] [J3].


As the alignment of an int on this platform is 4 bytes, 3 bytes are added after char C, and two bytes are added at the end of short B. Because of the padding, the addresses of the data in this structure are evenly divisible by 4. This is called structure member alignment. Obviously, the size of the structure in memory grows as a consequence.