Summary of memory alignment

Today, I participated in a small training before entering the job. During the training, the teacher talked about memory alignment. I have been in touch with it before, but I didn’t go into it. The teacher talked about it today, and I checked the information when I came back. The following is my memory alignment. understand.

Memory alignment can be said to be transparent to most software engineers. Memory alignment should be managed by the compiler. The feature of C language is that it is powerful and flexible, and it allows you to operate on memory. If you want to understand the deeper and lower-level things, you must have a certain understanding of memory alignment.

First why we need to align memory:

1) The reason of the platform: not all platforms can access any data at any address, some hardware platforms can only access certain types of data at certain addresses, otherwise it will be abnormal;

2) Performance issues: In order to access aligned data, the processor needs to make two memory accesses;

Alignment rules:

Usually we are discussing the layout of the data of the structure in memory. First, the first data is placed at the position where the offset is 0, and the layout of the subsequent data is based on the data itself and the default "alignment coefficient" of the system or by presetting Compile the smaller one among the "alignment coefficients" set by #pragma pack().

Finally, just pay attention to the roundness, that is to say, the size of the memory space occupied by the final structure is an integer multiple of the system default "alignment coefficient" or the "alignment coefficient" set by the precompiler.

for 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);
	printf("&b=%p\n",&x1.b);
	printf("&a=%p\n",&x1.c);
	printf("&b=%p\n",&x1.d);
	printf("%d",sizeof(x1));
	return 0;
}

Through the results, we can see that first b is placed where the offset is 0, and then a is long long, accounting for 8 bytes, and the pre-compilation setting is 4 bytes, so 3 bytes will be reserved after b , and so on, and finally added 3 bytes to meet the roundness requirements.

Guess you like

Origin blog.csdn.net/daida2008/article/details/41949715