Reason: Many computer systems place restrictions on the allowable addresses for the primitive data types, requiring that the address for some type of object must be a multiple of some value k (typically 2, 4, or 8). Such alignment restrictions simplify the design of the hardware forming the interface between the processor and the memory system.
Note: the IA32 hardware will work correctly regardless of the alignment of data. However, Intel recommends that data be aligned to improve memory system performance.
Alignment with Linux: Linux follows an alignment policy where 2-byte data types (e.g., short) must have an address that is a multiple of 2, while any larger data types (e.g., int, int *, float, and double) must have an address that is a multiple of 4.
Note: a multiple of 2 means the least significant bit of the address of an object of type short must equal 0. Similarly, any object of type int, or any pointer, must be at an address having the low-order two bits equal to 0.
Alignment with Microsoft Windows: Microsoft requires a stronger alignment requirement - any k-byte (primitive) object must have an address that is a multiple of k. In particular, it requires that the address of a double be a multiple of 8.
Note: malloc must be designed so that they return a pointer that satisfied the worst-case alignment restriction for the machine it is running on, typically 4 or 8.
For structures, the compiler may need to insert gaps in the field allocation to ensure that each structure element satisfies its alignment requirement. The compiler must also ensure that the structure has some required alignment for its starting address. In addition, the compiler may need to add padding to the end of the structure so that each element in an array of structures will satisfy its alignment requirement.
No comments:
Post a Comment