阿神2017-04-17 11:10:55
Take the opportunity to answer this question and review the basic knowledge yourself. Let’s get to the point:
First, understand the basic concepts:
Memory alignment, also commonly known as data alignment, is a computer that places some restrictions on the legal addresses of data types, requiring that the address of a certain type of object must be a multiple of a certain value K (usually 2, 4 or 8) .
Secondly, understand the purpose of data alignment:
This alignment restriction simplifies the hardware design of the interface between the processor and the memory system.
Currently, the views of major software and hardware manufacturers:
Hardware such as IA32 will work regardless of alignment, but it is recommended to align the data to improve the performance of the memory system.
Currently, the alignment strategies of mainstream operating systems:
The address of 2-byte data types (such as short) in Linux systems must be a multiple of 2, while the address of larger data types (such as int, int*, float, and double) must be a multiple of 4;
The policy of Windows system is more strict. The address of any K-byte basic object must be a multiple of K, K=2, 4, 8. Especially for a double or long The address of long type data should be a multiple of 8.
Finally, two small examples are given. Assume that the interface (data bus) between a processor and memory is 8 bytes (i.e. 64 bits), that is, the minimum unit read/written by the processor each time is 8 bytes.
Example 1: Store a double variable i
The misaligned part in the above figure causes the original one memory operation (0,7) to become two times (0,7), (8,15).
Example 2: Storing a structure variable
struct s {
int i;
char c;
int j;
};
In the above figure, for the purpose of data alignment, the structure will be filled when storing it. For different data structures, the filling methods are different. Some are filled in the middle part, and some are filled in the end part, all to ensure alignment. It should be noted that for this kind of structure filling, it is necessary to ensure not only the alignment of the data types within the structure, but also the alignment of the entire structure.
PS: Finally, I recommend a book worth reading carefully: In-depth Understanding of Computer Systems (Original Book 2nd Edition). The above quotations are also quoted from the content of this book.