Byte alignment in C Language struct

Source: Internet
Author: User

Statement, the following content is reproduced from: http://www.blogjava.net/hjh132/archive/2008/03/17/186849.html and
Http://blog.csdn.net/xuxinshao/article/details/2244297

 

What are the sizes of the following struct in VC?
Struct mystruct
{
Double M4;
Char M1;
Int m3;
};
Struct mystruct {
Char M1;
Double M4;
Int m3;
};
# Pragma pack (push) // save alignment status
# Pragma pack (16) // set to 16-byte alignment
Struct Test
{
Char M1;
Int m3;
Double M4;
};
# Pragma pack (POP) // restore alignment
If your answers are not 16, 24, or 16, I believe the following content is very helpful to you.
1. Structure of sizeof applications
See the following structure:
Struct mystruct
{
Double dda1;
Char DDA;
Int type
};
What will happen if sizeof is used for the structure mystruct? What is sizeof (mystruct? Maybe you
The following is the result:
Sizeof (mystruct) = sizeof (double) + sizeof (char) + sizeof (INT) = 13
However, when the above structure is tested in VC, you will find that sizeof (mystruct) is 16. You know why
Will such a result be obtained in VC?
In fact, this is a special processing of variable storage by VC. To speed up CPU storage
The starting address is aligned. By default, VC specifies that the starting address of each member variable is relative to the ending address.
The offset of the starting address must be a multiple of the number of bytes occupied by the variable type. The following lists common types
Alignment mode (vc6.0, 32-bit system ).
Type alignment (offset of the starting address of the variable to the starting address of the structure)
The Char offset must be sizeof (char), that is, a multiple of 1.
The short offset must be a multiple of sizeof (short), that is, 2.
The Int offset must be a multiple of sizeof (INT), that is, 4.
The float offset must be a multiple of sizeof (float), that is, 4.
The double offset must be sizeof (double), that is, a multiple of 8.
When each member variable is stored, it applies for space in sequence according to the order in which the structure appears.
Adjust the position in full mode. The vacant byte VC is automatically filled. At the same time, to ensure that the size of the structure is the byte edge of the Structure
The number of bounds (that is, the number of bytes occupied by the type that occupies the maximum space in the structure ).
After the variable is applied for space, the vacant bytes are automatically filled as needed.
The following uses the previous example to illustrate how VC stores the structure.
Struct mystruct
{
Double dda1;
Char DDA;
Int type
};
When allocating space for the above structure, VC is the first according to the sequence and alignment of the member variables.
The member dda1 allocates space. The starting address is the same as the starting address of the structure (the offset 0 is exactly sizeof (doub
The member variable occupies the sizeof (double) = 8 bytes. Then, the second member DDA is allocated with null values.
The offset of the next allocable address to the starting address of the structure is 8, which is a multiple of sizeof (char ).
Therefore, the DDA is stored in an alignment where the offset is 8. This member variable occupies sizeof (char) = 1 word.
Next, allocate space for the third member type. Then, the next address that can be allocated is the starting address of the structure.
The offset of is 9, not a multiple of sizeof (INT) = 4. To meet the offset constraints of alignment
Fill 3 bytes (these three bytes do not have anything), then the next address that can be allocated starts with the structure
The offset of the Start address is 12, which is a multiple of sizeof (INT) = 4. Therefore, the type is stored in the location where the offset is 12.
The member variable occupies sizeof (INT) = 4 bytes. At this time, the member variables in the entire structure have been allocated space, total
The occupied space is 8 + 1 + 3 + 4 = 16, which is exactly the number of bytes boundary in the structure (that is,
The number of bytes occupied by the Type sizeof (double) = 8), so no vacant bytes need to be filled. So the whole
Structure size: sizeof (mystruct) = 8 + 1 + 3 + 4 = 16, three of which are automatically filled by VC, no
Put anything meaningful.
Next, let's take another example to change the position of the member variable of mystruct above to the following:
:
Struct mystruct
{
Char DDA;
Double dda1;
Int type
};
How much space does this structure occupy? In the vc6.0 environment, we can obtain that sizeof (mystruc) is 24. End
Based on the space allocation principles mentioned above, we will analyze how VC allocates space for the above structure. (To put it simply
Ming)
Struct mystruct
{
Char DDA; // The offset is 0. The alignment is satisfied and the DDA occupies 1 byte;
Double dda1; // the offset of the next available address is 1, not sizeof (double) = 8
// Multiple. You need to add 7 bytes to make the offset 8 (the alignment is satisfied ).
// Method). Therefore, VC automatically fills in 7 bytes, and dda1 is stored at an offset of 8
// Address, which occupies 8 bytes.
Int type; // the offset of the next available address is 16, which is twice that of sizeof (INT) = 4.
// Number, which meets the alignment of int, so no VC auto-fill is required.
// Put the address at the offset of 16, which occupies 4 bytes.
}; // All member variables are allocated space. The total size of the space is 1 + 7 + 8 + 4 = 20, not a structure.
// Number of knots (that is, the number of bytes occupied by the largest space type in the structure sizeof
// (Double) = 8), so four bytes need to be filled to meet the structure size
// Sizeof (double) = a multiple of 8.
Therefore, the total size of this structure is: sizeof (mystruc) is 1 + 7 + 8 + 4 + 4 = 24. The total size is 7 + 4 = 11 bytes.
It is automatically filled by VC, and nothing makes sense.
The special processing of structured storage by VC does increase the speed of CPU storage variables, but sometimes it also brings some trouble
We also eliminate the default alignment of variables. We can set the alignment of variables by ourselves.
# Pragma pack (n) is provided in VC to set the variable to n-byte alignment. N-byte alignment means variable Storage
There are two types of offsets for the starting address: first, if n is greater than or equal to the number of bytes occupied by the variable, the offset is biased.
The shift must meet the default alignment. Second, if n is less than the number of bytes occupied by the type of the variable, the offset
The default alignment mode is not required because the number is a multiple of N. The total size of the structure also has a constraint, which is divided into the following two conditions:
: If n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be
A multiple of the space occupied by the variable;

Otherwise, it must be a multiple of N. The following is an example of its usage.
# Pragma pack (push) // save alignment status
# Pragma pack (4) // set to 4-byte alignment
Struct Test
{
Char M1;
Double M4;
Int m3;
};
# Pragma pack (POP) // restore alignment
The size of the above structure is 16, and the storage is analyzed below. First, space is allocated for M1, and its offset is 0, which meets
We set our own alignment mode (4-byte alignment). M1 occupies 1 byte. Then we start to allocate space for M4.
The offset is 1 and three bytes need to be supplemented. In this way, the offset must be a multiple of N = 4 (because sizeof (double) is large.
At N), M4 occupies 8 bytes. Then allocate space for M3. At this time, the offset is 12, which must be a multiple of 4.
4 bytes. At this time, space has been allocated for all member variables. A total of 16 bytes are allocated, which is a multiple of N. For example
If we change # pragma pack (4) to # pragma pack (16), the size of the structure is 24.
(Please analyze it by yourself)

 

Change the default byte alignment of the C Compiler
By default, the C compiler allocates space for each variable or data unit based on its natural limitations. Generally, you can use the following method to change the default peer condition:
· With the pseudo command # pragma pack (n), the C compiler will align according to n Bytes.
· Use the pseudo command # pragma pack () to cancel the custom byte alignment.

In addition, the following method is provided:
· _ Attribute (aligned (N) to align the structure members to the natural boundary of n Bytes. If the length of a member in the structure is greater than N, the maximum member length is used for alignment.
· _ Attribute _ (packed): cancels the optimization alignment of the structure during compilation and alignment according to the actual number of bytes occupied.

The first method above n = 1, 2, 4, 8, 16... is more common.

Below isCsdn ForumHot questions:

 

Interview Questions from companies such as Intel and Microsoft

# Pragma pack (8)

Struct S1 {
Short;
Long B;
};

Struct S2 {
Char C;
S1 D;
Long long E;
};

# Pragma pack ()

Question
1. sizeof (S2) =?
2. How many bytes are left behind C in S2 and then D?

ThanksRedleaves)The result is as follows:

The sizeof (S2) result is 24.
An important condition for member alignment is that each member is aligned separately. That is, each member is aligned in its own way.
That is to say, although alignment by 8 bytes is specified above, not all Members are alignment by 8 bytes. the alignment rule is that each member has a smaller alignment according to its type alignment parameter (usually the size of this type) and the specified alignment parameter (8 bytes here. in addition, the length of the structure must be an integer multiple of all alignment parameters used.
In S1, member A is 1 byte, which is aligned by 1 byte by default, and the specified alignment parameter is 8. Among the two values, 1 and a are aligned by 1 byte. Member B is 4 bytes, the default value is 4-byte alignment. In this case, it is 4-byte alignment, so sizeof (S1) should be 8;
In S2, C is the same as a in S1. It is aligned by 1 byte, while D is a structure. It is 8 bytes. What is its alignment? For the structure, its default alignment is the largest of all its members using alignment parameters, and S1 is 4. therefore, member D is aligned in 4 bytes. the member e is 8 bytes, which is aligned by 8 bytes by default. It is the same as the specified one, so it is connected to the boundary of 8 bytes. At this time, 12 bytes are used, therefore, four bytes are added, and the member e is placed starting from 16th bytes. at this time, the length is 24 and can be divisible by 8 (member e is aligned by 8 bytes. in this way, a total of 24 bytes are used.
A B
Memory layout of S1: 11 **, 1111,
C s1.a s1. B d
Memory layout of S2: 1 ***, 11 ***, 1111, *** 11111111

There are three important points:
1. Each Member is aligned in its own way, and the length can be minimized.
2. The default alignment of complex types (such as structures) is the alignment of its longest member, so that the length can be minimized when the member is a complex type.
3. The alignment length must be an integer multiple of the largest alignment parameter in the member. This ensures that each item is bounded when processing arrays.

In addition, for arrays, such:
Char A [3]; in this way, its alignment is the same as writing three char, that is, it is still aligned by 1 byte.
If you write: typedef char array3 [3];
The alignment of array3 type is still aligned by 1 byte, rather than by its length.
Whatever the type, the alignment boundary must be 1, 2, 4, 8, 16, 32, 64.

 

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.