Bytes alignment in Linux

Source: Internet
Author: User

1. Concept of memory address alignment

A Method for arranging and accessing data in computer memory, including Basic Data Alignment and Structure Data Alignment.

In a 32-bit system, the data bus width is 32, and 4 bytes of data can be read each time. The address bus is 32 and the maximum addressing space is 4 GB. However, because the bitwise A [0] ~ A [1] is not used for addressing. Therefore, it can only access the address space multiple of 4, but the addressing space is still 2 ^ 30 * characters long = 4 GB.

Therefore, in the memory, the minimum two hand addresses of the basic types except the member variables in the struct are 0. The Basic Data Alignment means that the offset address of the data in the memory must be a multiple of a word to Improve the Performance of Data Reading. To align data, you must insert some bytes at the end of the previous data and the start of the next data. This is the Data Alignment of the structure.


Ii. Influence of Non-Alignment

For example, if the address of int A is 0x00fffff3, its bytes are distributed in 0x00fffff3 ~ In 0x00fffff6 space, to read this int, the CPU must read 0x00fffff0 and 0x00fffff4 memory twice and process the intermediate results. Two times of memory access will waste a lot of time, because the memory access speed is much lower than the speed of CPU processing instructions.


3. Alignment of the memory address of the struct

The struct itself must be 4-byte aligned, and its member variables are subject to the following processing rules.

The default alignment between Microsoft and GNU for 32-bit structure members in X86 architecture is as follows:

Char 1-byte alignment

Short 2-byte alignment

Int 4-byte alignment

Float 4-byte alignment

Double windows is 8-byte alignment, Linux is 4-byte alignment

When the address alignment required by the member variables behind a member is large, enter some bytes. And the total size of the struct is a multiple of the maximum alignment. Therefore, some characters may be entered at the end.

Because of the above structure alignment, the structure members are sorted in ascending or descending order, which can reduce the space occupied by the structure. In this way, the access efficiency to the entire structure is increased (the usage is small, and the total access count can be reduced ).

Another way to improve efficiency is to merge some members with a small number of bytes into a large number of members to form the Union type.


4. Criteria

In fact, the details of byte alignment are related to the specific compiler implementation, but generally, three criteria are met:

1. The first address of the struct variable can be divisible by the size of its widest basic type member;

2. The offset of each member of the struct to the first address of the struct is an integer multiple of the member size. If necessary, the compiler will add the padding byte between the members;

3. The total size of the struct is an integer multiple of the size of the widest basic type of the struct. If necessary, the compiler will add the padding byte after the last member.


5. Basic Concepts

Byte alignment: data is stored in byte units in the computer storage system. The space occupied by different data types is different. For example, INTEGER (INT) Data occupies 4 bytes, character (char) data occupies one byte, short INTEGER (short) Data occupies two bytes, and so on. To quickly read and write data, a computer stores data at the starting position of an address by default. For example, integer data (INT) is stored at the starting position where the address can be divisible by four by default, character data (char) can be stored in any address location (divisible by 1), and short integer data is stored in the starting location where the address can be divisible by 2. This is the default byte alignment.


6. Structure Length Method

1. All members are the same (or contain arrays and the array data type is the same as that of other members of the struct ):
Struct length = Member Data Type length × number of members (sum of member lengths );
Length of the array in the struct = length of the array data type × Number of array elements;

2. When the members are different and do not include other struct;
(1) analyze the length of each member;
(2). Find out the maximum length of the member M (the length of the struct must be an integer multiple of the member );
(3). Divide the struct into several parts based on the position where the maximum member length appears;
(4) The length of each part is added once, and an integer multiple of the minimum m value greater than the sum is obtained.
(5) The sum of the lengths of each part is the length of the struct.

3. When other struct types are contained:
(1) analyze the length of each member;
(2) The length of a struct is analyzed based on B and does not change with the position;
(3) analyze the length of each member (the Member is the member length of the structure analysis) and obtain the maximum value;
(4) If the maximum length of a member is a member of a struct, it is divided by the demarcation points of the struct members;
If other members have the maximum length, the member is a demarcation point;
Find the length of each segment, and find an integer multiple of the minimum m greater than the sum, that is, the length of this part.
(5) The sum of the lengths of each part is the length of the struct.


VII. Empty struct S5 {}; sizeof (S5); // result 1

The size of the "null struct" (excluding data members) is not 0, but 1. Imagine how a variable with "no space occupied" can be separated by an address and two different "Empty struct" variables. Therefore, the variable "Empty struct" must also be stored, in this way, the compiler can only allocate one byte of space for occupying space.


8. struct S4 {char a; long B; static long C; // static };

Static variables are stored in the global data zone, and the size of the space allocated by the sizeof computing stack is not counted. The size of S4 is 4 + 4 = 8.

# The Pragma pack (n) command sets 1.2.4 alignment. In Linux, the maximum number of 4. # pragma pack () commands is four by default.


9. Union

The length of Union depends on the length of the member variable with the maximum length. That is, the member variables in the Union are placed in overlapping places, and their starting addresses are the same.

In fact, each member of Union (shared body) is stored at the same address, and only one member can be stored at every moment. In this way, it is required to meet the following requirements when allocating memory units:
1. In general, the storage space occupied by the shared object type is the storage space occupied by its longest member;
2. if the longest bucket does not meet the integer division relationship for the element type of other members (for example, int A [5] is 4, the maximum space is automatically extended;
Let's take a look at this Code:

Union mm {char a; // dollar length 1 int B [5]; // dollar length 4 double C; // dollar length 8 int d [3];};

Originally, the mm space should be sizeof (INT) * 5 = 20; but if it is only 20 units, how many double (8 bits) can be saved? Two and a half? Of course not. Therefore, the space of mm must be extended to an integer multiple of 20 and the space required by other Members, that is, 24.
Therefore, the Union bucket first looks at which of its members occupies the largest space, and compares it with the meta length of other Members. If it can be divisible, it will be fine.

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.