Understanding of alignment values

It took a while to understand the reasons for the alignment of the variable addresses in the compiler, and now record my understanding:

In fact, different systems will set a different natural alignment for each variable. The natural alignment value under the 32-bit system is 4, and the natural alignment value under the 64-bit system is 8. This is to match the bytes processed by each read and write memory. The 32-bit machine is fixed at 4 bytes each time, and the 64-bit machine is fixed at 8 bytes each time. The advantage of this is that for each reading of a certain value, it can be exactly the same as the byte stored in the cpu Boundary alignment makes the number of readings for each type of variable the least, without the following situations:
Double type reading, assuming that the cpu reads 4 bytes each time

In the case of setting natural alignment, only two memory loads are required (the bytes read into the cpu are just double data), but due to the disorderly arrangement, processing this double type variable requires three readings of the memory (Pictured above).
If the alignment value of each type of variable is not a natural alignment value, but is set to the byte size of each variable, you will find that the minimum number of reads can also be achieved:
This is the case where the alignment value of each data type is the number of bytes occupied by each
in fact, the purpose of setting the alignment value is to make The least number of reads is a way to trade space for time, because this may cause the storage of variables to be stored due to the alignment value, and the storage of different types of data are often not close together, and there will be many gaps.
The natural alignment value of 4 is sufficient to improve efficiency (on a 32-bit machine), but in order to minimize space consumption, we will change the alignment values ​​of different types of variables into the corresponding byte size.
But if you want to ensure that the address of the data is stuck on the boundary of the byte block read into the cpu, so as to avoid reading the cpu to find the data by offset, you have to set the alignment value of each type of data to the corresponding system every time The number of bytes read and written.

Guess you like

Origin blog.csdn.net/qq_51690757/article/details/112498128