Understanding of C + + memory alignment

Source: Internet
Author: User

The program compiler's special handling of the storage of the structure does increase the speed of the CPU storage variables, but sometimes it also brings some trouble, we also block out the default alignment of the variable, we can set the alignment of the variable.

The #pragma pack (n) is provided in the compiler to set the variable to n-byte alignment.

N-byte alignment means that the offset of the starting address at which the variable is stored is in two cases:

First, if n is greater than or equal to the number of bytes consumed by the variable, the offset must satisfy the default alignment.

Second, if n is less than the number of bytes occupied by the type of the variable, then the offset is a multiple of n and does not satisfy the default alignment.

The total size of the structure also has a constraint, divided into the following two kinds of 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 amount of space occupied by the variable occupying the largest space;

Otherwise, it must be a multiple of n.

The important rules

1, each member of a complex type is stored in memory sequentially in the order in which they are declared, and the address of the first member is the same as the address of the entire type;

2, Each member is aligned separately, that is, each member is aligned in its own way , and minimize the length of the rule is each member by its type alignment parameters (usually the size of this type) and Specifies the alignment parameter in ; (= in the complex type, not the overall alignment of the struct, etc.

3, the data member of the structure , union , or class, the first place is placed at the offset of 0, after each data member's alignment, according to the value specified by #pragma pack and the data member itself length two medium ratio The smaller one, that is, when the value specified by the #pragma pack equals or exceeds the length of all data members, the size of the specified value will have no effect ;

4, the alignment of a complex type (such as a structure) is based on the value of the smaller n_min between the data member with the largest length in the struct and the specified value of the #pragma pack.

This allows the length to be minimized when the member is a complex type;(refers to the overall alignment)

5, the calculation of the overall length of the structure must take the n_min integer times of all the alignment parameters used, not enough to fill the empty byte ; that is, take the integer multiple of the largest value in all the alignment parameters used , because the alignment parameters are 2 of the n-th square, so that when the array is processed, each item is guaranteed to be aligned at the boundary;

The length of the whole complex structure: (1) The longest data member length in the complex structure and the minimum length of "Set default Length" N_min (2) The whole actual length of complex type (according to the calculation results of the respective member alignment rules) takes the integer multiples of n_min, And if there is spare, spare.

Optimal storage, but performance may not be optimal.

Note: Alignment (alignment refers to the m_selft of the data type in memory from the starting length, where n is the length of this data member M_selft),

If struct {char A, float b, int c}

because: Char 1bit, float 2Bit, int 4bit.

Actual memory usage: a:[0] X b:[2][3] c:[4][5][6][7]

That is: [A][][b][b][c][c][c][c], because the a:1 first address, b=2 need to align to the address length 2 [2][3], c=4 need to align to the length of 4 address

  

Alignment implementations: Normally, when we write programs, we don't need to consider alignment issues. The compiler chooses the alignment strategy for the target platform for us. Of course, we can also notify the compiler to pass the precompiled instructions and change the alignment of the specified data. However, because we generally do not need to care about this problem, because the editor to the data storage alignment, and we do not understand, often will be confused about some problems. The most common is the sizeof result of the struct data structure, unexpectedly. To do this, we need to understand the alignment algorithm. function:Specifies the structure , union, and packing alignment of the class member; (Set alignment) Grammar: #pragma pack ([show] | [Push | pop] [, identifier], N) Description: 1,pack provides control of the data declaration level, does not work on the definition, 2, does not specify parameters when calling pack.n will be set to default value, default 8 bytes; 3, once you change the alignment of the data type, the direct effect is to occupy memory reduction, but performance will fallSyntax specific analysis: 1,show: Optional parameters, display the number of bytes of the current packing aligment in the form of a warning message, 2,push: Optional parameters; Press the current specified packing alignment value to stack the operation, The stack here is the internal compiler stack, while the current packing alignment is set to n, and if n is not specified, the current packing alignment value is stacked; 3,pop: optional parameter; from internal The topmost record is removed from the compiler stack, and if n is not specified, the current stack top record is the new packing alignment value, and n becomes the new packing aligment value if n is specified If identifier is specified, the record in the internal compiler stack will be caught by the pop until identifier is found, then the pop is Identitier, and the packing is set The alignment value is the record at the top of the current stack, and if the specified identifier does not exist in the internal compiler stack, the pop operation is ignored; 4,identifier: optional parameter; When used with push, Give the record a name that is currently pressed into the stack, and when used with a pop, pops all the record from the internal compiler stack until the identifier is popped out, and if identifier is not found, The pop operation is ignored; 5,n: optional parameter; Specifies the value of the packing.in bytes, the default value is 8, the legal values are 1, 2, 4, 8, 16, respectively.

emphasize one thing: #pragma Pack (4)struct{char buf[3];word A;} KK; #pragma pack ()

The principle of alignment is min (sizeof (word), 4) =2, so it is 2-byte aligned instead of 4-byte alignment we think .

Here are three important points:
1. Each member is aligned in its own way and can minimize the length
2. The default alignment of a complex type, such as a structure, is the alignment of its longest member, so that the length can be minimized when the member is a complex type
3. The length of the alignment must be an integer multiple of the largest alignment parameter in the member , so that each item is bound to the boundary when the array is processed


To add, for arrays, for example: Char a[3];

This way, its alignment is the same as writing 3 char respectively. That is, it is still aligned by 1 bytes .
If write: typedef char ARRAY3[3];
Array3 This type of alignment is still aligned by 1 bytes, not by its length.
Regardless of the type, the aligned boundary must be a 1,2,4,8,16,32,64 ....

Example One: #pragma pack (4)classtestb{ Public:intAA;//first member, placed at [0,3] offset,(struct internal member alignment, int = 4)
Char a; //The second member, with a length of 1, #pragmaPack4), take a small value, which is 1, so this member is aligned in one byte and placed in the offset [4] position. (struct internal member type alignment, 1 < 4 for minimum 1-byte alignment) Shortb//the third member, the self-length 2, #pragmaPack4), take a small value, take 2, press 2 byte to align, so put in the offset [6,7] position.(struct internal member type alignment, 2 < 4 for minimum 2-byte alignment)
CharC//The fourth one, the self-length is 1, placed in [8] position. (struct internal member type alignment, 1 < 4 for minimum 1-byte alignment) };
[5] address, because short B is 2 length, it needs to be skipped.
Visible, This class actually occupies a memory space of 9 bytes  sizeof(int4;
Description
 Length of the overall complex structure:
(1) The longest data member length in complex structure and the minimum length of "Set default Length" N_min
(2) The whole actual length of complex type takes the whole multiple of n_min, and if there is spare, it can be filled.

Example Two:#pragmaPack (2)classtestb{ Public:intAa//first member, placed at [0,3] offset, (struct internal member type alignment, Int=4 > 2 min. 2 byte alignment) CharA//The second member, which has a length of 1, #pragmapack (4), takes a small value, which is 1, so the member is aligned in one byte and placed in the offset [4] position. (struct internal member type alignment, 1 < 2 take 1-byte alignment)  Shortb//The third member, its own length 2, #pragmapack (4), take 2, by 2 byte alignment, so placed in the offset [6,7] position. (struct internal member type alignment, 2 = 2 for 2-byte alignment) CharC//The fourth one, the self-length is 1, placed in [8] position. (struct internal member type alignment, 1 < 2 for minimum 1-byte alignment) };
[5] address, because short B is 2 length, it needs to be skipped.
Visible, This class  actually occupies 9 bytes of memory space . According to Rule 5, 
sizeof (int2;

Example Three:#pragmaPack (4)classtestc{ Public:CharA//The first member, placed in the [0] offset position, Shortb//The second member, which has a length of 2, #pragmapack (4), takes 2 and is aligned by 2 bytes, so it is placed in the offset [2,3] position. CharC//The third one, its own length is 1, placed in [4] position. };
[1] address, because short B is 2 length, you need to skip and navigate directly to the alignment address of a multiple of 2. [2] [3]. The actual memory consumption of the entire class is 5 bytes, as a whole by min (sizeof( Short),4) =2 aligned, so the result is sizeof (TESTC)=6;

Example four:structtest{CharX1;//The first member, placed in the [0] position,
because short x2 is 2 length, you need to skip [1] and navigate directly to the alignment address of a multiple of 2. [2] [3]. ShortX2;//The second member, with its own length of 2, is aligned by 2 bytes, so it is placed in the offset [2,3] position,floatX3;//The third member, with its own length of 4, is aligned by 4 bytes, so placed in the offset [4,7] position,CharX4;//The fourth Chen, with its own length of 1, is aligned by 1 bytes, so it is placed at offset [8],so the actual memory consumption of the entire struct is 9 bytes, but given that the overall structure alignment is 4 bytes (the default alignment), the entire structure takes up 12 bytes of space.

Example Five:#pragmaPack (8)struct S1{ ShortA//The first one, placed in [0,1] position,
because B has a length of 4, it needs to "align addresses at 4 times times", so it ignores [2][3]
Longb//The second one, the length of itself is 4, by min (4,8) = 4 aligned , so placed in the [4,7] position so the actual memory consumption of the struct is 8 bytes , and the alignment of the struct is min (sizeof(Long), pack_value) = 4 bytes , so the entire structure takes up 8 bytes of space. struct S2{CharC//The first one, placed in [0] position,S1D//second, according to rule four, alignment is min (4,pack_value) = 4 bytes, so put in [4,11] position,Long LongE//The third one, with a length of 8 bytes, is aligned by 8 bytes, so it is placed in the [16,23] position,}; So the actual memory consumption is 24 itself, the overall alignment is 8 bytes, so the entire structure occupies 24 bytes of space. #pragmaPack ()so:sizeof(s2) = -, S2 c is empty after 3 bytes followed by D.

Endl

Understanding of C + + memory alignment

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.