What is byte alignment and why is it aligned?

Source: Internet
Author: User
Tags pack reserved
The memory space in modern computers is divided by Byte, in theory it seems that access to any type of variable can start from any address, but the reality is that when accessing a particular type of variable, it is often accessed at a specific memory address, which requires all types of data to be spatially arranged according to certain rules, Instead of sequentially one by one emissions, that's the alignment.
The effect and reason of alignment: the processing of storage space varies greatly with each hardware platform. Some platforms can only access certain types of data from certain specific addresses. For example, some architectures have an error when accessing a variable that is not aligned, so programming must ensure byte alignment in this architecture. Other platforms may not have this, but the most common is the loss of access efficiency if the data storage is not aligned according to their platform requirements. For example, some platforms read each time from the even address, if an int (assuming 32-bit system) if the location of the place where the even address begins, then a read cycle can be read out of the 32bit, and if it is stored at the beginning of the odd address, it takes 2 read cycles, The 32bit data can be obtained by piecing together the high and low bytes of the two read-out results. Obviously, the reading efficiency is much lower.

Two. The effect of byte alignment on the program:
Let's take a look at some examples (32bit,x86 environment, GCC compiler):
The structure is defined as follows:
struct A
{
int A;
Char b;
Short C;
};

4Byte
         |---------|
| A |
|----|----|
| b-| C-|
|---------|



struct B
{
Char b;
int A;
Short C;
};

|--------|
|b |
|--------|
| A |
|--------|
| C |
|--------|


The lengths of the various data types on the 32-bit machine are now known as:
Char:1 (Signed and unsigned)
Short:2 (Signed and unsigned)
Int:4 (Signed and unsigned)
Long:4 (Signed and unsigned)
Float:4 Double:8
So what's the size of the top two structures?
The result is:
sizeof (Strcut A) value is 8
sizeof (struct B) has a value of 12.

struct A contains 4-byte-length int one, 1-byte-length char one and 2-byte length of short data one, B is the same; The result above is because the compiler wants to align the data members spatially. The above is the result of the alignment according to the compiler's default settings, then we can not change the compiler's default alignment settings, of course. For example:

#pragma pack (2)/* Specify 2-byte alignment */
struct B
{
Char b;
int A;
Short C;
};
#pragma pack ()/* To cancel the specified alignment, restore the default alignment */
The sizeof (struct B) value is 8.


Modify the alignment value to 1:
#pragma pack (1)/* Specify 1-byte alignment */
struct B
{
Char b;
int A;
Short C;
};
#pragma pack ()/* To cancel the specified alignment, restore the default alignment */
sizeof (struct B) has a value of 7.

Later we explain the role of #pragma pack ().

Three. What are the principles for the compiler to align?

Let's start by looking at four important basic concepts:
1. The alignment value of the data type itself: for char type data, its own alignment value is 1, for the short type is 2, for the int,float,double type, its own alignment value is 4, the unit byte.
2. The structure's self-aligning value: The value of its member that is the largest of its own alignment value.
3. Specify the alignment value: The specified alignment value when #pragma pack (value) is values.
4. Valid alignment values for data members and structs: The value of the data member (data type) and the self-aligning values of the structure and the values that are small for the specified alignment values. (data members are aligned to the structure and are naturally aligned.)

With these values, we can easily discuss the members of a specific data structure and its own alignment. The valid alignment value n is the value that is ultimately used to determine how the data is stored, most importantly. A valid alignment of n is the "alignment on n", which means that the data "holds the starting address%n=0". Data variables in the structure are emitted in a defined order of precedence. The starting address of the first data variable is the starting address of the structure. The member variables of the struct should be aligned with the emission, and the structure itself should be rounded according to its own valid alignment value (that is, the total length of the struct member variable is required to be an integral multiple of the effective alignment value of the struct, as the following example understands). This makes it easy to understand the values of several examples above.

Example Analysis:
analysis example B;
struct B
{
Char b;
int A;
Short C;
};
Suppose B starts discharging from the address space 0x0000. In this example, the specified alignment value is not defined, and in the author's environment, the value defaults to 4. The first member variable B has its own alignment value of 1, which is smaller than the specified or default alignment value of 4, so its valid alignment value is 1, so its storage address 0x0000 conforms to 0x0000%1=0. The second member variable A has its own alignment value of 4, so the valid alignment value is also 4. So it can only be stored in the starting address of 0x0004 to 0x0007 four consecutive byte space, review 0x0004%4=0, and immediately close to the first variable. The third variable, C, has its own alignment value of 2, so the valid alignment value is also 2, which can be stored in the two byte space of 0x0008 to 0x0009, conforming to 0x0008%2=0. So everything from 0x0000 to 0x0009 is stored in B content. Then look at the data structure B's own alignment value for its variable maximum alignment value (here is B) so is 4, so the structure of the effective alignment value is also 4. 0x0009 to 0x0000=10 bytes, (10+2)%4=0 according to the requirements of the structural rounding. So 0x0000a to 0x000b is also occupied by struct B. So B has a total of 12 bytes from 0x0000 to 0x000b, sizeof (struct B) = 12; In fact, if this is the case it has aligned the satisfied byte, because its starting address is 0, so it must be aligned, the reason is to add 2 bytes later, Because the compiler is in order to achieve the access efficiency of the array of structures, imagine if we define an array of struct B, then the first struct starts with a 0 no problem, but the second structure? As defined by the array, all elements in the array are next to each other, and if we do not add the size of the structure to the integer multiples of 4, Then the starting address of the next structure will be 0x0000a, which obviously does not satisfy the structure's address alignment, so we want to add the structure to an integer multiple of the effective alignment size. In fact, for char type data, its own alignment value is 1, for the short type is 2, for Int,float, A double type with its own alignment value of 4, these existing types of self-aligning values are also based on arrays, only because the lengths of these types are known, so their own alignment values are known.
Similarly, analyze the above example C:
#pragma pack (2)/* Specify 2-byte alignment */
struct C
{
Char b;
int A;
Short C;
};
#pragma pack ()/* To cancel the specified alignment, restore the default alignment */
The first variable B has its own alignment value of 1, the specified alignment value is 2, so its valid alignment value is 1, assuming that C starts with 0x0000, then B is stored in 0x0000, conforms to 0x0000%1= 0, the second variable has its own alignment value of 4, and the alignment value is 2, so the valid alignment value is 2. So the order is stored in 0x0002, 0x0003, 0x0004, 0x0005 four consecutive bytes, in accordance with 0x0002%2=0. The third variable, C, has its own alignment value of 2, so the valid alignment value is 2, which is stored sequentially
In 0x0006, 0x0007, in accordance with 0x0006%2=0. So from 0x0000 to 0x00007 a total of eight bytes is stored in the C variable. and C has its own alignment value of 4, so the valid alignment value for C is 2. And 8%2=0,c only takes up eight bytes of 0x0000 to 0x0007. So sizeof (struct C) =8.


Four. How do I modify the compiler's default alignment values?
1. In the VC IDE, you can modify this: [project]| [settings],c/c tab category of the Code generation option of the struct Member alignment modified, the default is 8 bytes.
2. When encoding, you can change this dynamically: #pragma pack. Note: It is pragma instead of progma.

---------------------------------------------------------
· Using the pseudo-directive #pragma pack (n), the C compiler will be aligned in N bytes.
· Use pseudo-Directives #pragma pack () to cancel custom byte alignment.

---------------------------------------------------------
· __attribute ((aligned (n))) that aligns the members of the structure to the N-byte natural boundary. If the length of a member in the structure is greater than n, the length of the maximum member is aligned.
· __ATTRIBUTE__ ((packed)), cancels the optimization alignment of the structure during compilation, aligned according to the actual number of bytes consumed.


Five. What do we consider in programming for byte alignment?
If you want to consider saving space when programming, then we only need to assume that the first address of the structure is 0, then the various variables are arranged according to the above principles, the basic principle is to make the variables in the structure from small to large declaration of the type size, Minimize the amount of space in the middle. There is another way to make space for the efficiency of time, we show the space to be filled to align, such as: There is a space-time approach is to explicitly insert reserved members:
struct a{
Char A;
Char reserved[3];//use space to change time
int b;
}

The reserved member has no meaning to our program, it just fills the space to achieve byte alignment, and of course even without this member the compiler will automatically fill us with the alignment, and we add it just to play an explicit reminder.


Six. Possible pitfalls of byte alignment:
Many of the pitfalls of alignment in code are implicit. For example, when forcing type conversions. For example:
unsigned int i = 0x12345678;
unsigned char *p=null;
unsigned short *p1=null;

p=&i;
*p=0x00;
p1= (unsigned short *) (P 1);
*p1=0x0000;
The last two lines of code, from the odd boundary to access the unsigned short variable, clearly do not conform to the rules of alignment. On x86, similar operations can only affect efficiency, but on MIPS or SPARC, it can be an error because they require byte alignment.

Seven. How to find problems with byte alignment:
If an alignment or assignment problem occurs, first view
1. Compiler's big little side settings
2. See if the system itself supports non-aligned access
3. If the support depends on whether the alignment is set or not, if there is no access, you need to add some special decorations to flag its special access operation.

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.