当前位置:网站首页>Wrong again, byte alignment and the use of pragma pack
Wrong again, byte alignment and the use of pragma pack
2022-07-19 13:01:00 【Li Xiaoyao】
Focus on 、 Official account of star standard , Straight to the highlights
The article citations :https://www.cnblogs.com/dabiao/archive/2010/04/15/1712458.html
C The compiler's default byte alignment ( Nature is opposite to the world )
By default ,C The compiler allocates space for each variable or data unit according to its natural bounding condition .
In structure , The compiler aligns each member of the structure according to its natural bounds (alignment) Conditional allocation space . Members are stored in memory in the order in which they are declared ( There may be empty bytes inserted between members ), The address of the first member is the same as the address of the whole structure .
C The compiler's default structure member natural alignment condition is “N Byte alignment ”,N That is, the length of the member data type . Such as int The natural boundary condition of type member is 4 Byte alignment , and double The natural boundary condition of structural members of type is 8 Byte alignment . If the starting offset of the member is not in the “ Default natural boundary condition ” On , Then add an appropriate number of empty bytes after the previous node .
C The default natural boundary condition of the compiler structure is : The maximum natural boundary condition required in all members of the structure . If the sum of the lengths of the members of the structure is not “ Integral multiple of the natural boundary condition of the whole structure , Fill in empty bytes after the last member .
Example 1( Analyze the default byte pair boundary condition of each member of the structure and the default byte pair boundary condition of the whole structure ):
struct Test
{
char x1; // member x1 by char type ( Its starting address must be 1 Byte to byte ), Its offset address is 0 char x2; // member x2 by char type ( Its starting address must be 1 Byte to byte , Its offset address is 1 float x3; // member x3 by float type ( Its starting address must be 4 Byte to byte ), The compiler is in x2 and x3 Two empty bytes are filled between , Its offset address is 4 char x4; // member x4 by char type ( Its starting address must be 1 Byte to byte ), Its offset address is 8 };
because Test In the structure , The largest member is flaot x3, Because the natural boundary condition of this structure is 4 Byte alignment . Then the length of the structure is 12 byte , The memory layout is 1100 1111 1000.
Example 2:
#include <stdio.h>//#pragma pack(2)typedef struct
{
int aa1; //4 Byte alignment 1111 char bb1;//1 Byte alignment 1 short cc1;//2 Byte alignment 011 char dd1; //1 Byte alignment 1 } testlength1;
int length1 = sizeof(testlength1); //4 Byte alignment , Occupied bytes 1111 1011 1000,length = 12
typedef struct
{
char bb2;//1 Byte alignment 1 int aa2; //4 Byte alignment 01111 short cc2;//2 Byte alignment 11 char dd2; //1 Byte alignment 1 } testlength2;
int length2 = sizeof(testlength2); //4 Byte alignment , Occupied bytes 1011 1111 1000,length = 12
typedef struct
{
char bb3; //1 Byte alignment 1 char dd3; //1 Byte alignment 1 int aa3; //4 Byte alignment 001111 short cc23//2 Byte alignment 11
} testlength3;
int length3 = sizeof(testlength3); //4 Byte alignment , Occupied bytes 1100 1111 1100,length = 12
typedef struct
{
char bb4; //1 Byte alignment 1 char dd4; //1 Byte alignment 1 short cc4;//2 Byte alignment 11 int aa4; //4 Byte alignment 1111 } testlength4;
int length4 = sizeof(testlength4); //4 Byte alignment , Occupied bytes 1111 1111,length = 8int main(void)
{
printf("length1 = %d.\n",length1);
printf("length2 = %d.\n",length2);
printf("length3 = %d.\n",length3);
printf("length4 = %d.\n",length4);
return 0;
} Change the default boundary condition ( Specify the opposite boundary )
· Using pseudo instructions #pragma pack (n),C The compiler will follow n Byte alignment .
· Using pseudo instructions #pragma pack (), Cancel custom byte alignment .
At this time , The alignment rule is :
1、 Data member alignment rules : structure (struct)( Or in association with (union)) Data members of , The first data member is placed in offset by 0 The place of , In the future, the alignment of each data member is in accordance with #pragma pack The specified value and the length of the data member itself , The smaller one is going to .
2、 structure ( Or in association with ) The overall alignment rule of : After the data members are aligned , structure ( Or in association with ) Alignment itself , The alignment will follow #pragma pack Specified values and structures ( Or in association with ) In the maximum data member length , The smaller one is going to .
combination 1、2 infer : When #pragma pack Of n When the value equals or exceeds the length of all data members , This n The size of the value will have no effect .
therefore , When using pseudo instructions #pragma pack (2) when ,Test The size of the structure is 8, The memory layout is 11 11 11 10.
One thing to note , When a structure contains a substructure , Members in the substructure follow #pragma pack The specified value and the maximum data member length of the substructure , Align the smaller one . Examples are as follows :
#pragma pack(8)
struct s1{
short a;
long b;
};
struct s2{
char c;
s1 d;
long long e;
};
#pragma pack()sizeof(s2) As the result of the 24.S1 The memory layout of is 1100 1111,S2 The memory layout of is 1000 1100 1111 0000 1111 1111.
Example :
#include <stdio.h>#pragma pack(2)
typedef struct
{
int aa1; //2 Byte alignment 1111 char bb1;//1 Byte alignment 1 short cc1;//2 Byte alignment 011 char dd1; //1 Byte alignment 1 } testlength1;
int length1 = sizeof(testlength1); //2 Byte alignment , Occupied bytes 11 11 10 11 10,length = 10
typedef struct
{
char bb2;//1 Byte alignment 1 int aa2; //2 Byte alignment 01111 short cc2;//2 Byte alignment 11 char dd2; //1 Byte alignment 1 } testlength2;
int length2 = sizeof(testlength2); //2 Byte alignment , Occupied bytes 10 11 11 11 10,length = 10
typedef struct
{
char bb3; //1 Byte alignment 1 char dd3; //1 Byte alignment 1 int aa3; //2 Byte alignment 11 11 short cc23//2 Byte alignment 11
} testlength3;
int length3 = sizeof(testlength3); //2 Byte alignment , Occupied bytes 11 11 11 11,length = 8
typedef struct
{
char bb4; //1 Byte alignment 1 char dd4; //1 Byte alignment 1 short cc4;//2 Byte alignment 11 int aa4; //2 Byte alignment 11 11 } testlength4;
int length4 = sizeof(testlength4); //2 Byte alignment , Occupied bytes 11 11 11 11,length = 8int main(void)
{
printf("length1 = %d.\n",length1);
printf("length2 = %d.\n",length2);
printf("length3 = %d.\n",length3);
printf("length4 = %d.\n",length4);
return 0;
}in addition , There's another way :
· __attribute((aligned (n))), Align the active members of the structure in n Byte on the natural boundary . If the length of a member in a structure is greater than n, Then align according to the length of the largest member .
· __attribute__ ((packed)), Cancels the optimal alignment of the structure during compilation , Align according to the actual number of bytes occupied .
The above n = 1, 2, 4, 8, 16... The first way is more common .
Copyright notice : Source network of this paper , Free delivery of knowledge , The copyright belongs to the original author . If involves the work copyright question , Please contact me to delete .
‧‧‧‧‧‧‧‧‧‧‧‧‧‧‧‧ END ‧‧‧‧‧‧‧‧‧‧‧‧‧‧‧
Pay attention to my WeChat official account , reply “ Add group ” Join the technical exchange group according to the rules . Click on “ Read the original ” See more sharing , Welcome to share 、 Collection 、 give the thumbs-up 、 Looking at .边栏推荐
- Metal organic framework material / polymer composite zif-8/p (TDA co HDA) | zinc oxide [email protected] (FE) composite nan
- S32K148_ Can drive (bare metal development)
- Competition notes: numpy learning notes
- 【Pygame 学习笔记】7.事件
- Is the career direction of test / development programmers over 35 a turning point in the workplace?
- npm err! [email protected] build: `umi build`
- 通货收缩的市场何时反转?我们该如何操作?2020-03-13
- Will the market halve? What investment opportunities are there? 2020-03-11
- MOF customized product | n-k2ti4o9/g-c3n4/uio-66 ternary composite | paper based au-aginse2-zif-8 Nanocomposite
- How can MySQL delete data tables and associated data tables
猜你喜欢

AE如何制作星云粒子特效

Audio common terminal anatomy - never make a mistake again

Gold nanoparticles modified mil-101 framework material (AuNPs / mil-101) / loaded cof-tppa-1 (Au NPs / cof-tppa-1) | Qiyue reagent

Azkaban 安装文档

整理了一份通用的内存管理驱动代码

Structure memory alignment, bit segment, union

标签球问题

Ultrasonic sensor (ch101 & ch201) - I

Lazy to the bone, I am too lazy to write articles in CSDN. I write articles based on selenium simulation

力扣198-213 打家劫舍Ⅰ、Ⅱ——动态规划
随机推荐
收益风险比:投资机会最重要指标 2020-03-14
Common bug precautions of audio control
CMOS开关学习(一)
Competition notes: numpy learning notes
Interview difficulties: difficulties in implementing distributed session, this is enough!
OSSImport迁移之路
最懂你的服装设计师是AI?让用户 “凭心意” 生成数字服装#Adidas OZWORLD
XML modeling (easy to learn)
虞美人·寄公度
Lazy to the bone, I am too lazy to write articles in CSDN. I write articles based on selenium simulation
最小交換次數
XML文件解析
Metal organic framework / nitrogen carbide nano sheet (uio-66/hocn) composite | mil-101 loaded Au Pd alloy nanoparticles | chemical reagent MOF customization
Metal organic framework material / polymer composite zif-8/p (TDA co HDA) | zinc oxide [email protected] (FE) composite nan
Yunxi focuses on store broadcast solutions to accelerate global layout
C语言进阶——自定义类型:结构体 枚举 联合
LeetCode_ Prefix and_ Medium_ 523. Continuous subarrays and
Figure execution engine (II)
Google developer community sharing - flutter animation sharing has been released
GO 单元测试