10.struct memory alignment

First of all, why struct memory alignment is performed? The CPU reads data with a fixed block size, which is related to the number of bits of the computer. A 64-bit host CPU reads blocks of 8 bytes at a time, and a 32-bit host CPU reads blocks of 4 bytes at a time. Knowing that the host reads a fixed block size, let's assume a scenario like this. On a 32-bit machine, 4 bytes of data are distributed in two blocks. Assume that the bytes are distributed in bytes 2 to 5. That is 0-3 is the first block, and 4-7 is the second block. For such four bytes of data, two blocks need to be taken out, which reduces the efficiency of CPU reading to a certain extent. If we directly discard the 2-3 bytes in the first block of the above data and put them all into the second block, then our CPU only needs to read it once, which improves the overall efficiency of the computer to a certain extent. But you can also find that space is wasted. Practice has proven that this exchange of space for time is worthwhile.
The size of a block read by the CPU here is called The system default alignment byte number or < a i=4>alignment modulus ratio. There are four main rules for struct memory alignment: Rule 1: The starting address of the first member is 0. (The first member Offset)Rule 2:The starting address of the internal member of the struct is the integer that is the smaller of the system's default alignment bytes and the size of the member. times. (Ordinary member alignment)Rule 3:When structures are nested, the starting address of the structure members is the largest member size within the structure member. Integer multiples, the occupied address is calculated according to the size of the structure member itself. (Alignment of structure type members)Rule 4:After all internal members of the structure have been aligned, align the entire structure. The overall memory size occupied by the structure must be an integer multiple of the smaller of the largest variable type in the structure and the system's default number of aligned bytes. (The structure is aligned as a whole)




From the above explanation, we can see that rule one will definitely be used when there are members, rule two will definitely be used when the number of members is greater than or equal to 2, and rule three will definitely be used when a structure is nested inside a structure. Use, Rule 4 will be used unconditionally.
So the two most common situations are: 1. Rule 1, Rule 2, and Rule 4 are used together. 2. Use all four rules.

Use Rule 1, Rule 2, and Rule 4 for memory alignment

Insert image description here

Use all four rules

Insert image description here

Reference blog: https://www.csdn.net/tags/NtDaUg2sMjUzNTItYmxvZwO0O0OO0O0O.html

Guess you like

Origin blog.csdn.net/qq_43847153/article/details/126807060