Deep analysis of struct structure byte alignment _c language in C + +

Source: Internet
Author: User

What is byte alignment and why is it aligned?

The memory space in modern computers is divided by byte, theoretically, it seems that access to any type of variable can begin at any address, but the reality is that access to a particular type of variable is often at a specific memory address, which requires that various types of data be arranged in space according to certain rules, Instead of sequencing one after another, that's the alignment.

The function and reason of the alignment: each hardware platform has a great difference in the processing of storage space. Some platforms have access to certain types of data only from certain addresses. For example, some of the architecture of the CPU to access a variable does not have to be aligned, when the error occurs, then programming in this architecture must ensure byte alignment. Other platforms may not, but the most common is the loss of access efficiency if the data is not aligned according to its platform requirements. For example, some platforms start every time from the even address, if an int (assuming 32-bit system) if stored in the beginning of the even address, then a read cycle can read out the 32bit, and if the location of the beginning of the odd address, it will take 2 reading cycles, The 32bit data can be obtained by piecing together the high and low byte of the results of two readings. Obviously, the reading efficiency is much lower.

Storage Allocation for structures
the compiler allocates memory for each member in the order of the member list of the struct body, and the additional memory space may be available for padding when the member needs to meet the correct boundary alignment requirements when it is stored. A 32-bit system allocates a maximum of 4 bytes per byte, and a 64-bit system allocates a maximum of 8 bytes.
The following chart is the basic type of data memory size and default pair of Zimo in different systems:
Note: The length of the memory that the pointer occupies is determined by the system, with 32 bits (4 bytes) under the 32-bit system and 64 bits (that is, 8 bytes) under the 64-bit system.

No alignment of #pragma pack macros
Alignment Rules:

The starting storage location of a struct must be divisible by the largest data type in the structure.
The starting position of each data member store is an integer multiple of its own size (for example, int is 4 bytes in 32-bit machine, the int member is to be stored from the integer-Multiple address of 4).
The total size of the structure (that is, the result of the sizeof) must be the largest number of integers to the Zimo in the member of the struct. If not, the empty bytes are automatically populated as needed.
A struct body contains another member of the struct body, the member of the containing structure is to be stored from the maximum number of integer multiples of the Zimo within its original structure body. (for example, struct A contains elements such as char,int,double in the struct b,b, and b should be stored as an integral number of 8.) )
The structure body contains an array member, such as Char A[3], whose alignment is the same as writing 3 char, which means it is still aligned by one byte. If you write: typedef char Array[3],array This type of alignment is still aligned by one byte rather than by its length 3.
A struct body contains a shared-body member, the shared-body member is to be stored from the integer multiple address of the Zimo number within its original shared body.
Now give us a structure, and we will analyze it for win-32 and Linux-32,

Example 1:

struct MyStruct
{
  char A;
  int b;
  Long double C;
};

Answer:
Win-32 bit system:
The above figure shows that the maximum number of Zimo for the structure is sizeof (long double) = 8, assuming that mystruct is stored from the address space 0x0000. Char is 1 bytes, so a is stored in 0x0000; int is 4 bytes, according to the rule, the starting address of the B store must be the integer multiple of its Zimo number 4, so a will automatically populate the empty byte space 0x0001-0x0003, so b is stored in 0x0004-0x0007. A long double is 8 bytes, and because a 32-bit system allocates up to 4 bytes at a time, the 0x0008-0x000b is allocated first, and the 0X000C-0X000F is continued because of insufficient storage, so c is stored in 0x0008-0x000f, Because the total storage space at this time is 4+4+8=16, then 16 satisfies the integer multiple of the maximum Zimo number sizeof (long double); therefore, sizeof (mystruct) = 16 bytes.
Linux-32 bit system:

The above figure shows that the maximum Zimo number of the structure is 4, and that the mystruct is stored from the address space 0x0000. Char is 1 bytes, so a is stored in 0x0000; int is 4 bytes, according to the rule, the starting address of the B store must be the integer multiple of its Zimo number 4, so a will automatically populate the empty byte space 0x0001-0x0003, so b is stored in 0x0004-0x0007. A long double is 12 bytes, because a 32-bit system allocates up to 4 bytes at a time, 0x0008-0x000b is allocated first, and because there is not enough storage space, the 0X000C-0X000F continues to be allocated and the storage C is still not satisfied, then the 0x0010-0x0013 is continued. So c is stored in 0x0008-0x0013, because the total storage space at this time is 4+4+12=20; 20 satisfies the integer multiple of the maximum of Zimo number 4; therefore, sizeof (mystruct) = 20 bytes.

Note: All of the following examples are implemented under WIN-32
Example 2:

struct b{ 
  char A; 
  int b; 
  char c; 
};

The above figure shows that the maximum number of Zimo for the structure is sizeof (int) = 4, and that B begins to store 0x0000 from the address space. Char is 1 bytes, so a is stored in 0x0000; int is 4 bytes, according to the rule, the starting address of the B store must be the integer multiple of its Zimo number 4, so a will automatically populate the empty byte space 0x0001-0x0003, so b is stored in 0x0004-0x0007. C is also a char type, so c is stored in 0x0008, at which point the total size of the struct B is 4+4+1=9 bytes, then 9 cannot satisfy the integer multiple of the maximum of Zimo number 4, so automatically fills the space 0x0009-0x000b after C so that it satisfies the multiple of the maximum number of Zimo numbers, The storage space of the final structure body B is 0x0000-0x000b; sizeof (b) = 12 bytes.
Example 3: Empty structure body

struct c{ 
  };
sizeof (c) = 0 or sizeof (c);

C is an empty structure, accounting for 0 bytes in C, and 1 bytes in C + +.

Example 4: The structure has static members

struct d{ 
   char A; 
   int b; 
   static double C; static member 
};

Static member variables are stored in the global data area, the memory space is allocated at compile time, so the total memory size of the structure is not made any contribution; therefore, sizeof (D) =4+4=8 bytes
Example 5: The structure Body contains the structure body

struct e{ 
  int A; 
  Double b; 
  float C; 
}; 
struct f{ 
  char e[2]; 
  int F; 
  Short h; 
  struct E i; 
};

The maximum number of Zimo in structure e is sizeof (double) = 8; and sizeof (e) =8+8+8=24 bytes; in structure F, in addition to struct member E, the other maximum Zimo number is sizeof (int) = 4 and because the maximum number of Zimo in the structure body e is sizeof (double) = 8; Therefore, the maximum number of Zimo to the Zimo number of the structure F is 8; therefore, sizeof (f) =4+4+8+24=40 bytes.
Example 6: The structure contains a common body

Union union1 
{ 
  long A; 
  Double b; 
  Char name[9]; 
  int c[2]; 
struct e{ 
  int A; 
  Double b; 
  float C; 
  Union1 myunion; 
};

The maximum alignment pattern in the common body is sizeof (double) = 8, then sizeof (union1) = 16, and the maximum Zimo number of struct E is 8; then sizeof (e) =8+8+8+16=40 bytes.
Example 7: struct Body contains pointer member

typedef struct a{ 
  char A; 
  int b; 
  float C; 
  Double D; 
  int *p; 
  char *pc; 
  Short e; 
} A

The size of the pointer members contained in the struct is determined by the system type, and since this is analyzed under the win-32 bit system, the pointer size is 4 bytes, so the maximum number of Zimo for struct A is sizeof (double) = 8; then sizeof (A) =4+4+8+8+4+4+8= 40 bytes.

Alignment of #pragma pack macros exists

#pragma pack (n)  //compiler will snap to n bytes 
#pragma pack ()   //Cancel custom byte alignment

Alignment rules:
Structure, union, or data members of a class, the first place where the offset is 0, the alignment of each data member in the future, the value specified by the #pragma pack, and the smaller of the Zimo number.
Example 8: Number of pairs of Zimo specified

#pragma pack (2)/* Specifies 2-byte alignment */ 
struct g{ 
  char b; 
  int A; 
  Double D; 
  Short C; 
}; 
#pragma pack ()/* To cancel the specified alignment and restore the default alignment */

The maximum Zimo number of member variables in structure G is sizeof (double) = 8; Because the number of Zimo is 2, the Zimo number of the structure G is the smaller 2, then sizeof (g) =2+4+8+2=16; Because 16 is an integer multiple of 2, no padding is required.

Summarize
when parsing the structure byte alignment, first determine whether the number of Zimo is specified by using the #pragma pack () macro definition, and according to the situation, two scenarios are analyzed, and different results are obtained for different systems.

Add:
you can declare data by using __declspec (#) in Visual C + + (align (#)) to align with the # byte
The following commands can be used under GUN C:
__ATTRIBUTE__ ((aligned (n)) to align the member of the structure to the N-byte natural boundary. If the length of a member in the structure is greater than N, it is aligned according to the length of the maximum member
__attribute__ ((__packed__)), cancels the optimized alignment of the structure during compilation, and aligns to the actual number of bytes occupied.
C++11 New keyword Alignas (n)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.