Links to the original text: http://harlon.org/2018/04/05/cpluscplusmemorypack/
C/C++ Memory Alignment Byte Alignment Strategy
Strct memory completion is one of the compulsory questions in the written test, but sometimes the way stuct memory alignment is very confusing. Here we comb the strategy of memory alignment.
strategy
- Rule 1: The front address must be an integral multiple of the back address, not aligned.
- Rule 2: The entire address must be an integer multiple of the largest byte.
- Rule 3: Specify # pragma pack(n), the entire address is an integer multiple of n.
Example
Take 32-bit environment as an example (64-bit environment pointer is 8 bytes, the rule is the same):
struct s { char *p; // 4 byte char c; // 4 byte rule 1 int a; // 4 byte }; sizeof(s) = 12; struct s { char *p; // 4 byte char c; // 1 byte char ch[2]; // 3 byte rule 1 int x; // 4 byte }; sizeof(s) = 12; struct s { char p; // 4 byte rule 1 int x; // 4 byte char c; // Rule 2 of 4 bytes }; sizeof(s) = 12; struct s { char p; // 4 byte rule 1 int x; // 4 byte char c; // 4 byte struct a { char *b; // 4 byte long y; // 4 byte } inner; // 8 byte }; sizeof(s) = 20; struct s { char p; char x; struct a { char b; int y[10]; } inner; char c; }; sizeof(s) = 56; struct s { char p; char x; int f:1; int b:2; char c:1; }; sizeof(s) = 12; struct s { char c; // 4 byte rule 1 union u { char *p; short x; } inner; // Four byte }; sizeof(s) = 8; union s { char c; struct u { char p; int x; } inner; }; sizeof(s) = 8; #pragma pack(2) struct s { char *p; // 4 byte char x; // 2 byte rule 3 int a; // 4 byte }; sizeof(s) = 10; #pragma pack(1) struct s { char *p; char x; int a; }; sizeof(s) = 9; #pragma pack(8) struct s { char *p; char x; int a; }; sizeof(s) = 16;