C language learning - byte alignment

byte alignment

Byte alignment is the location of data in memory.

Assuming that the memory address of a variable is exactly an integer multiple of its length, it is said to be naturally aligned. For example, under 32-bit cpu. Assuming that an integer variable has an address of 0x00000004, it is naturally aligned.

The need for byte alignment

The fundamental reason for the need for byte alignment is the efficiency of CPU access to data. If the address of the integer variable is not naturally aligned. For example, if it is 0x00000002, the CPU needs to access the memory twice if it takes its value. The first time it takes a short from 0x00000002-0x00000003, and the second time it takes a short from 0x00000004-0x00000005 and then combines to get the required data. Assuming that the variable is at the address of 0x00000003, it needs to access the memory three times, the first time is char, the second time is short, the third time is char, and then the integer data is obtained by combining.

Assuming the variable is in a natural alignment position, the data can be retrieved only once.

Byte alignment rules

For standard data types, its address is simply an integer multiple of its length. Non-standard data types are aligned according to the following principles:

 
1. Array: Aligned according to the basic data type, the first one that is aligned will naturally be aligned.


2. Union: Align according to the data type with the largest length it contains.
3. Structure: Each data type in the structure must be aligned.

Sample

struct stu{
   char sex;
   int length;
   char name[10];
  };

In this, sex is 1 byte, and then when length is encountered, 3 null bytes need to be added after sex, because length occupies 4 bytes, and after name occupies 10 bytes, it becomes 18 words section is not properly aligned, so add two null bytes. becomes 20 bytes.

Change the alignment method

__attribute__Options

This is to change the alignment method, such as the following example:

struct stu{
   char sex;
   int length;
   char name[10];
  }__attribute__ ((aligned (1))); 

This is a total of 15 bytes, due to alignedchanging the natural alignment byte to 1 byte.

So overall it's down.

Same as the following statement:

struct stu{
   char sex;
   int length;
   char name[10];
  }__attribute__ ((packed)); 

This is also 15 bytes. packedMake structs use the smallest alignment possible.

Alignment must be declared

When designing communication protocols for different CPUs. Or the structure of registers when writing hardware drivers needs to be aligned by one byte. Align it even if it appears to be naturally aligned, so that different compilers do not generate the same code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324731300&siteId=291194637