Data Alignment

Source: Internet
Author: User

Syc109: Bakari Date: 2013.8.26

Data Alignment is actually the alignment of memory bytes. Today, I accidentally opened my previous notes and found that I have made many questions, but now I feel very new to me. I checked the reason and Method of Data Alignment online, and now I have sorted it out for further study and consolidation.

1. What is Data Alignment

1. the memory space in modern computers is divided by byte. Theoretically, it seems that access to any type of variables can start from any address, however, the actual situation is that access to specific variables is often performed at specific memory addresses, which requires various types of data to be arranged in space according to certain rules, instead of sequential emissions, this is alignment.

2. The data access address must meet certain conditions and be divisible by the Data Length. For example, the 1-byte data is already aligned. The address of the 2-byte data is divided by 2, and the 4-byte data address is divided by 4.

3. Data Alignment is not part of the memory structure of the operating system, but part of the c p u structure.

4. When c p u accesses data with correct alignment, it runs most efficiently. When the memory address of the Data modulus is 0, the data is aligned. For example, the w o r d value should always start from the address divided by 2, and the d w o r d value should always start from the address divided by 4. When the data values that c p u tries to read are not correctly aligned, c p u can perform either of the two operations. That is, it can generate an exception condition or execute multiple alignment memory accesses to read the complete alignment data values.

Ii. Reasons for alignment

1. Currently, various hardware platforms are significantly different in terms of storage space processing. Some platforms can only access certain types of data from some specific addresses. This may not be the case for other platforms, but the most common problem is that alignment of data storage according to the requirements suitable for their platforms will result in a loss of access efficiency. For example, some platforms start from the even address each time they read data. If an int type (assuming 32-bit) is stored at the beginning of the even address, a read cycle can be read, if the data is stored at the beginning of the odd address, it may take two read cycles and splice the high and low bytes of the two read results to obtain the int data. Obviously, reading efficiency is greatly reduced. This is also a game of space and time.

2. Data Alignment is used to read data efficiently. If every time data is read in one byte and one byte, there is no need for alignment. There is no difference between this and reading one byte, that is, reading multiple times. However, data reading efficiency is not high. To increase the bandwidth for Data Reading, many parallel storage chips are used in the current generation of storage systems to improve reading efficiency.

Iii. Data Alignment implementation

Usually, we do not need to consider alignment when writing a program. The compiler selects an alignment policy suitable for the target platform for us. Of course, we can also notify the compiler to pass the pre-compilation command to change the Alignment Method for the specified data.

1. How exactly does the data align in the memory? How does the alignment details and alignment mode display the compiler? Please refer to this article, which makes it clear: Explain.

2. There are two ways to implement Data Alignment: natural alignment (default alignment) and forced alignment.

1) natural alignment

General compiler such as VS2003-VS2010, CB, Dev C ++ compiler alignment, the default is 8 bits, that is, # pragma pack (value) value = 8.

Let's look at a typical example.

1 # include <iostream> 2 using namespace STD; 3 4 struct a 5 {6 char _ IC1; 7 long _ il; 8 char _ ic2; 9 double _ id; 10 }; 11 // disrupt the order 12 struct B13 {14 char _ IC1; 15 char _ ic2; 16 long _ il; 17 double _ id; 18}; 19 int main () {20 cout <sizeof (a) <Endl; 21 cout <sizeof (B) <Endl; 22 23 return 0; 24}

Analysis:

For a: _ IC1 to take up one byte, the long type is 4 bytes. In order to make the subsequent long type natural alignment, three bytes need to be added, represented by CC in the memory, that is, 3cc (the same below) is added, _ il occupies 4 bytes, and _ ic2 occupies 1 byte. To align double, 7cc is added, and then _ id occupies 8 bytes. Therefore, sizeof (A) = 1 + 3 + 4 + 1 + 7 + 8 = 24 bytes.

For B: Similarly, sizeof (B) = 1 + 1 + 2 + 4 + 8 = 16

Verification:

Summary:

The offset of each member variable's address relative to the start address of the structure is sizeof (type) or an integer multiple of it. The total size of a structure is an integer multiple of the largest sizeof type in its members. Therefore, when defining a struct, it is best to declare the variables in the structure according to the type size from small to large to reduce the space filled in the middle.

2) force alignment, that is, manually modifying # value in Pragma pack (value)

1 # include <iostream> 2 using namespace STD; 3 4 # pragma pack (4) // note! 5 struct a 6 {7 char _ IC1; 8 long _ il; 9 char _ ic2; 10 double _ id; 11}; 12 # pragma pack () 13 // disrupt the order 14 struct B15 {16 char _ IC1; 17 char _ ic2; 18 long _ il; 19 double _ id; 20}; 21 int main () {22 cout <sizeof (a) <Endl; 23 cout <sizeof (B) <Endl; 24 25 return 0; 26}

Note: sizeof (A) = 20

Analysis: only the number of bytes occupied by _ ic2 has been changed. The valid alignment value of _ ic2 is no longer the number of bytes of the double type, instead, it forces the minimum value of the alignment value and its alignment value (that is, the alignment value of the next type), 4 <8, so the valid alignment value is 4. therefore:

Sizeof (A) = 1 + 3 + 4 + 1 + 3 + 8 = 20

For the calculation of the valid alignment value above, a netizen summed it up very well. For details, refer:

Use the # pragma pack (n) to set the alignment coefficient. First, if n is greater than or equal to the number of bytes occupied by the member, the offset must meet the default alignment mode, that is, the natural alignment mode. 2. If n is less than the number of bytes occupied by the member type, the offset is a multiple of N, and the default alignment mode is not required. The total size of the structure also has a constraint, which is divided into the following two cases: 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 largest variable; otherwise, it must be a multiple of N.

4. The following are some typical examples for consolidation:

The answer is behind, and my answer is not necessarily correct. You can do it yourself and then verify it on the computer before coming for reference.

Example 1:
Struct practice1
{
Char _ sza [123];
Int _ Ib;
Float _ IC;
Double _ dd;
};
1. Find the size of this struct by default, and describe its memory layout in illustrated format.
2. If you add # pragma pack (2) and # pragma pack () to the struct, what is the size of the pack?

Example 2:

Struct practice2
{
Struct T1
{
Char _ Ca;
Int _ Ib;
Float _ FC;
} _ Objx;
Int _ id;
Char _ ie;
};
1. Find the size of this struct by default, and describe its memory layout in illustrated format.
2. If # pragma pack (4) and # pragma pack () are added to the struct, what is the size of the struct?

Example 3:

Struct practice3
{
Union T1
{
Char _ CT;
Double _ DT;
Int _ it;
} _ Ut;
Int _ IA;
Double _ dB;
};
1. Find the size of this struct by default, and describe its memory layout in illustrated format.
2. If you add # pragma pack (1) and # pragma pack () to the struct, what is the size of the pack?

Reference answer:

Analysis:

Example 1:

(1) The default alignment value is 8, starting from 0x0000, that is# Pragma pack (8)
Char _ sza [123]; 123 + CC ...... Cc = 124
Int _ Ib; 124 + 4 = 128
Float _ IC; 128 + 4 + CC +... + CC = 132 + 4cc = 136
Double _ dd; 136 + 8 = 144
(2) If# Pragma pack (2)
The memory distribution is: 123 + CC + 4 + 4 + 8 = 140

Example 2:

(1)# Pragma pack (8)

Struct T1
{
Char _ Ca; 1 + CC... + CC = 4
Int _ Ib; 4 + 4 = 8
Float _ FC; 8 + 4 = 12
} _ Objx; 12
Int _ id; 12 + 4 = 16
Char _ ie; 16 + 1 = 17 + CC +... + CC = 20
So the result is: 20

(2)If # pragma pack (4)
Then: 1 + CC + 4 + 4 + 4 + 1 + CC = 20

Example 3:

(1) If# Pragma pack (8)
Union T1
{
Char _ CT;
Double _ DT; 8
Int _ it;
} _ Ut; 8
Int _ IA; 8 + 4 + CC... + CC = 16
Double _ dB; 16 + 8 = 24
(2) If# Pragma pack (1)
The value is 8 + 4 + 8 = 20.

Verification:

 1 #include <iostream> 2 using namespace std; 3  4 struct Practice1 5 { 6     char _szA[123]; 7     int _iA; 8     float _iB; 9     double _iD;10 };11 12 struct Practice213 {14     struct T115     {16         char    _cA;17         int     _iB;18         float   _fC;19     }       _objX;20     int     _iD;21     char    _iE;22 };23 24 struct Practice325 {26     union T127     {28         char   _cT;29         double _dT;30         int    _iT;31     }   _uT;32     int     _iA;33     double  _dB;34 };35 36 int main(){37     cout << sizeof(Practice1) << endl;38     cout << sizeof(Practice2) << endl;39     cout << sizeof(Practice3) << endl;40     return 0;41 }

 1 #include <iostream> 2 using namespace std; 3  4 #pragma pack(2) 5 struct Practice1 6 { 7     char _szA[123]; 8     int _iA; 9     float _iB;10     double _iD;11 };12 #pragma pack()13 14 #pragma pack(4)15 struct Practice216 {17     struct T118     {19         char    _cA;20         int     _iB;21         float   _fC;22     }       _objX;23     int     _iD;24     char    _iE;25 };26 #pragma pack()27 28 #pragma pack(1)29 struct Practice330 {31     union T132     {33         char   _cT;34         double _dT;35         int    _iT;36     }   _uT;37     int     _iA;38     double  _dB;39 };40 #pragma pack()41 42 int main(){43     cout << sizeof(Practice1) << endl;44     cout << sizeof(Practice2) << endl;45     cout << sizeof(Practice3) << endl;46     return 0;47 }

OK. Have a good time!

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.