1. Why is byte alignment?
In a word, the access efficiency is improved. The access efficiency is related to machines. For example, some machines always retrieve data from even bytes. At the same time, the access efficiency is also related to the data type, for example, if an integer number can be obtained at one time, it is certainly the best, but because the machine always takes two accesses from the even byte, this will definitely reduce the efficiency.
2. Some Concepts in character alignment?
- # Pragma pack (n): indicates that the alignment byte of the machine is explicitly declared as n. We remember that this number is MA, and each machine has the default MA, in the previous sentence, we changed the MA. To restore the default MA of the system, the syntax is # pragma pack ()
- Effective alignment byte: The structure is used as an example for analysis. For each member in the structure, its own byte alignment requirements must satisfy at least an integer multiple of its own starting address, however, if MA is smaller than its own size, the number of alignment must be MA. The valid alignment byte is min (MA, Data Alignment byte) Wherever alignment is needed)
- When do I need to align? For a struct, each of its members must be aligned, and the size of the entire struct must be aligned.
3. Alignment principle (taking struct as an example)
- For each element in the struct, the alignment size is min (MA, its own size)
- The first address of the struct must be aligned with min (MA, maximum volume element size in the struct). Note that it is not min (MA, struct size)
- The final size of the struct must be min (MA, maximum volume in the struct) aligned.
- The default structure member of the C compiler is "N Bytes alignment", which is the length of the member data type. That is, if # pragma pack (n) is not used, it is equivalent to n infinity.
There are two other statements:
4. Note that the sizeof function takes the occupied stack space, so static members are not included.
References: 1. byte alignment (forced alignment and natural alignment) 2. Alignment instances (including union)
PS: This summary is just for myself, so I only want to figure it for my convenience, so it may not be very detailed. Of course, if you see some help, you can't do it well, if something is wrong, point it out.