Memory alignment details for C/C ++ and memory alignment details
1. What is memory alignment?
The computer system limits the location of basic data types in the memory. They will require the first address of these data types to be an integer multiple of the number (generally 4 and 8, let's look at the size of the struct.
#include
struct A{ char a; int b;};int main(){ printf("size of struct A is %d\n", sizeof(struct A)); return 0;}
Result:
1111deMacBook-Pro:digui a1111$ ./sizeofsize of struct A is 8
The result is 8, not 5, because of memory alignment.
1:
2
3
4
5: B
6
7
8
2. Why memory alignment?
It sacrifices space, accelerates cpu addressing, and speeds up reading memory data.
The memory is measured in bytes, but the processor does not store data in bytes. Generally, the memory is accessed in dual-byte, four-byte, eight-byte, 16-byte, or 32-byte format, these access units are memory access Granularity
For example, if there is no memory alignment, a 4-byte access granularity is used. If the int variable is placed in the address of 1, data in the read zone starts from 0. The first read zone ranges from 0 to 4, however, this is not completed after the event. The valid address is still 4 to 5. Then, for the second time, the read area ranges from 4 to 8. Then, the two valid data blocks are merged into the register, which requires a lot of work, if memory alignment exists and the storage starts from 0, you can read the data at one time without merging the data, which speeds up the efficiency,
3. The # pragma pack (n) is not aligned with the memory.
Add memory alignment
#include
struct A{ int a; char b; char c;};struct B{ char a; int b; char c;};int main(){ printf("size of struct A is %d\n", sizeof(struct A)); printf("size of struct B is %d\n", sizeof(struct B)); return 0;}
The results are as follows:
8 12
Then we use # pragma pack (n) to process memory alignment. For example, we use # pragma pack (1)
#include
#pragma pack(1)struct A{ int a; char b; char c;};struct B{ char a; int b; char c;};int main(){ printf("size of struct A is %d\n", sizeof(struct A)); printf("size of struct B is %d\n", sizeof(struct B)); return 0;}
All results
6 6
If you use # pragma pack (2)
The result is
6 8
We can understand that pack (n) and the first address of the struct member variable can start with n times.