Today took part in the pre-employment of the small training, the teacher talked about the memory of the alignment of the only, before contact, but did not delve into, today the teacher said, back to check the information, the following is my understanding of memory alignment.
Memory alignment can be said to be transparent to most software engineers, memory alignment should be the compiler to manage, C language is characterized by a powerful and flexible, he allows you to operate on the memory. If you want to understand the deeper underlying things, you have to have a certain understanding of memory alignment.
The first is why we need to align the memory:
1) Platform reason: Not all platforms can access arbitrary data at any address, some hardware platform can only access certain types of data at some addresses, otherwise abnormal;
2) Performance problem: In order to access the aligned data, the processor should make two memory accesses;
Rules for alignment:
Usually we are talking about the structure of the data in memory layout, first of the first data placed in the position of offset 0, the layout of the subsequent data according to the data itself and the system default "alignment coefficient" or by the pre-compiled #pragma pack () set by the "alignment factor" in the smaller one.
Finally, notice the rounding is good, that is, the final structure occupies the size of the memory space is the system default "alignment factor" or pre-compilation set "Alignment Factor" integer times.
As an example:
#include <stdio.h> #pragma pack (4) struct Xx{char b;long long a;int C;char D;}; #pragma pack () int main () {struct XX x1;printf ("&a=%p\n", &x1.a);p rintf ("&b=%p\n", &x1.b);p rintf (" &a=%p\n ", &x1.c);p rintf (" &b=%p\n ", &x1.d);p rintf ("%d ", sizeof (x1)); return 0;}
By the result we can see that the first B is placed at offset 0, then a long long, 8 bytes, precompiled set is 4 bytes, so B will be reserved 3 bytes, and so on, and finally added 3 bytes, is to meet the requirements of rounding.
Memory Alignment Summary