当前位置:网站首页>C language: Structure -- a detailed explanation of memory byte alignment
C language: Structure -- a detailed explanation of memory byte alignment
2022-07-25 02:25:00 【heart_ six thousand six hundred and sixty-two】
Preface :
We're learning c Language memory management is always amazing , Its smart memory management strategy , Complain over and over about its incomprehensible methods , Online information should not be too detailed , Or I didn't explain it clearly , Today, let's learn based on 32 Bit operating system Of course C Language : Memory byte alignment
tip: stay 32 In bit compile mode , Default to 4 Byte alignment ; stay 64 In bit compile mode , Default to 8 Byte alignment .
Catalog
2. Why should computers be aligned ?
3. Let's go straight to the code
There are two rules for alignment :
1. What is alignment ?
In modern computers, memory space is in bytes (byte) The division of , Theoretically, it seems that access to any type of variable can start at any address , But the actual situation is that when you access a specific variable, you often access it at a specific memory address , This requires All types of data are arranged spatially according to certain rules , and Instead of discharging sequentially one by one , This is alignment .
2. Why should computers be aligned ?
Each hardware platform has a big difference in the processing of storage space . Some platforms can only access certain types of data from certain addresses , Other platforms may not have this situation . But if the data storage is not aligned according to the requirements suitable for its platform , Loss of access efficiency .
For example, one int Data of type , If the address is 8, So it's easy , The number is 8 Memory addressing can be done once . If the number is 10, It's more troublesome ,CPU It is necessary to number 8 Memory addressing , Read 4 Bytes , Get the first half of the data , Then number it as 12 Memory addressing , Read 4 Bytes , Get the second half of the data , Then join the two parts together , To get the value of the data .
Try to put a data in one step , Avoid storing across steps , This is called memory alignment . stay 32 In bit compile mode , Default to 4 Byte alignment ; stay 64 In bit compile mode , Default to 8 Byte alignment .
3. Let's go straight to the code
Case a
#include <stdio.h>
void main(){
struct A{
char a;
short b;
int c;
};
printf( "size of struct A = %d \n", sizeof(struct A) );
}The output is :8 byte .
Let's look at the picture
First step :
First, the self alignment value is the largest ( That is to say int type ) yes 4 32 The alignment value of bit operating system is also 4, So the effective alignment value is 4
The second step :
The starting address of the storage member must be an integer multiple of the effective alignment value of the member
a yes char Type data , Occupy 1 Byte memory ;short Type data , Occupy 2 Byte memory ;int Type data , Occupy 4 Byte memory . therefore , Structure A The self alignment value of is 4. therefore ,a and b Make up 4 Bytes , So as to meet with c Of 4 Byte alignment . and a Only 1 Bytes ,a And b A byte is empty between . We know , The structure type data is stored in order, and the structure is arranged backward one by one
Case 2
#include <stdio.h>
void main(){
struct A{
short b;
int c;
char a;
};
printf( "size of struct A = %d \n", sizeof(struct A) );
}The output is :12 byte .
Let's look at the picture
First step :
The self alignment value is the largest ( That is to say int type ) yes 4 32 The alignment value of bit operating system is also 4, So the effective alignment value is 4
The second step :
The starting address of the storage member must be an integer multiple of the effective alignment value of the member
b yes short Type data , Occupy 2 Byte memory ;chart Type data , Occupy 1 Byte memory ;int Type data , Occupy 4 Byte memory . therefore , Structure A The self alignment value of is 4. therefore ,b One data account for 4 byte ( It was originally two bytes ),c One data account for 4 byte ,a One data account for 4 byte ( Originally a byte )
Analogy like this ( Aligned appearance )
Alignment rule
A term is used to explain :
Here we introduce four concepts
The alignment value of the data type itself ,
Specify the alignment value ,
The self alignment value of a structure or class ,
Data member 、 Valid alignment values for structs and classes
1) The alignment value of the data type itself : Is the self alignment value of the basic data type , such as char The self alignment value of type is 1 byte ,int The self alignment value of type is 4 byte .
2) Specify the alignment value : Precompiled orders #pragma pack (value) Specified alignment value value.
3) The self alignment value of a structure or class : The value with the largest self alignment value among its members , Like the above struct A The alignment value for is 4.
4) Data member 、 Valid alignment values for structs and classes : The smaller of the self alignment value and the specified alignment value .
There are two rules for alignment :
1、 First The self alignment value of the structure and Alignment value of the operating system comparison , take Small the Is the valid alignment value
Like this one down here The self alignment value of the structure is 4 The alignment value of the operating system is also 4, So the effective alignment value is 4
#include <stdio.h>
void main(){
struct A{
short b;
int c;
char a;
};
printf( "size of struct A = %d \n", sizeof(struct A) );
}
2、 The starting address of the storage member must be an integer multiple of the effective alignment value of the member .
Generally speaking, it's Each data type and Compare the valid alignment values Take the larger one Namely The last valid alignment value
#include <stdio.h>
void main(){
struct A{
short b;
int c;
char a;
};
printf( "size of struct A = %d \n", sizeof(struct A) );
}Or the code above ,b by short type (1 byte ) And valid alignment values (4 byte ) The larger value is 4 byte

边栏推荐
- Codeforces:d1. choosing carrots (easy version) [max min problem + control one side to make the other side as close as possible + thinking]
- Why can't reading more books improve your writing?
- Query the thread information of MySQL server (detailed explanation)
- Creating elements of DOM series
- Data integration | what are the tools for data integration at home and abroad?
- Scalar, vector, matrix calculus
- How to communicate with aliens
- Use Fiddler to capture apps
- Several application scenarios of NAT
- Thinkphp5.0.24 deserialization chain analysis
猜你喜欢

Yunyuanyuan (VIII) | Devops in depth Devops

Four redis cluster schemes you must know and their advantages and disadvantages

These 11 chrome artifacts are extremely cool to use

Industrial control safety PLC firmware reverse III

Sword finger offer 11. rotate the minimum number of the array

Actf questions (dropper+master_of_dns)

Server performance monitoring

Use SAP ui5 application to consume create and delete operations of OData in business application studio

I was forced to graduate by a big factory and recited the eight part essay in a two-month window. Fortunately, I went ashore, otherwise I wouldn't be able to repay the mortgage
![[hero planet July training leetcode problem solving daily] 20th BST](/img/25/2d2a05374b0cf85cf123f408c48fe2.png)
[hero planet July training leetcode problem solving daily] 20th BST
随机推荐
When does MySQL use table locks and row locks?
What are the important trends revealed by the release of "operator data viability index"?
"Ask the sky" is in place! Yu Jingchuan's "China Space Station" in 2013 is about to set sail in the sea of stars
Experienced the troubleshooting and solution process of an online CPU100% and the application of oom
Anacona has too many environments?? How to view your current environment in jupyter
R language uses logistic regression, ANOVA, outlier analysis and visual classification iris iris data set
Remove & lt; li&gt; Front blank distance
Vs2019 configuring Qt5 development environment
About the relationship between parent process and child process (UAC bypass idea)
Hcip - BGP - border gateway protocol
Simulation Implementation of [STL] string class
[system design] distributed key value database
[leetcode] 3. Longest substring without repeated characters - go language problem solution
Custom types in C language
Easy to master SSO single sign on, see this article
[hero planet July training leetcode problem solving daily] 20th BST
Peripherals: interrupt system of keys and CPU
Nacos service discovery data model
Actf questions (dropper+master_of_dns)
xts performance auto fix script


