byte alignment

1. Principles:
1. The members of the structure are self-aligned according to their own lengths.
Its own length, such as char=1, short=2, int=4, double=8,. The so-called self-alignment means that the memory address of the starting position of the member must be an integer multiple of its own length. For example, int can only start with addresses such as 0, 4, and 8.
2. The total size of the structure is an integer multiple of
the effective alignment value of the structure
. The length of the longest member in the structure is its valid value
2) When specified with #pragma pack(n), the smaller of n and the length of the longest member in the structure is its value. Valid alignment values ​​for data members, structures, and classes: the lesser of its own alignment and the specified alignment. Affects the offset and total size of each member
3) attribute((aligned (n))), so that the structure members acted on are aligned on the natural boundary of n bytes. If there are members in the structure whose length is greater than n, they are aligned according to the length of the largest member. Tell the compiler the address alignment of a structure or class or union or a variable (object) of a type when the address space is allocated. That is, if attribute ((aligned(m))) is applied to a type, when the variable of this type is allocated address space, its storage address must be aligned according to m bytes (m must be a power of 2.) ). And the space it occupies, that is, the size, is also an integer multiple of m, to ensure that when applying for continuous storage space, the address of each element is also aligned according to m bytes. Affects the size of the entire structure
attribute__ ((packed)), cancels the optimized alignment of the structure during compilation, and aligns it according to the actual number of bytes occupied.

2. Correctly handle byte alignment
   For standard data types, its address only needs to be an integer multiple of its length, while non-standard data types are aligned according to the following principles:
  Array: aligned according to the basic data type, the first one is aligned The latter is naturally aligned.
  Union: Align by the data type with the largest length it contains.
  Structure: Each data type in a structure must be aligned.

ps: Vc, Vs and other compilers default to #pragma pack(8), so testing our rules will be normal; note that gcc defaults to #pragma pack(4), and gcc only supports 1,2,4 alignment. The alignment value calculated in the three principles cannot be greater than the n value specified by #pragma pack

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324896073&siteId=291194637