C++ memory alignment rules

Three rules of memory alignment:

  1. For each member of the structure, the offset of the first member is 0, and the current offset of the following members must be an integer multiple of the current member type
  2. After all the data members in the structure are aligned in their respective memory, the structure itself needs to be aligned once to ensure that the memory occupied by the entire structure is the smallest integer multiple of the largest data member in the structure
  3. If there is a #pragma pack(n) precompiled instruction in the program, the alignment of all members is based on n bytes (that is, the offset is an integer multiple of n), and the current type and the type of the largest structure body are no longer considered
#include<iostream>
using namespace std;
struct A{
    char a;
    int b;
    short c;
};

struct B{
    short c;
    char a;
    int b;
};
int main(){
    cout<<sizeof(A)<<endl;
    cout<<sizeof(B)<<endl;
    return 0;
}

 

Take the above structure A as an example. The first member a is of type char and occupies 1 byte of space with an offset of 0. The second member b is of type int and occupies 4 bytes of space. According to rule 1, The offset of b must be an integer multiple of the int type, so the compiler will insert a 3-byte buffer after the a variable to ensure that the offset of b (4 bytes) is an integer multiple of the b type (currently just Is 1 times), the third member c is of type short. At this time, the offset of c is exactly 4+4=8 bytes, which is already an integral multiple of type short, so there is no need to fill buffer words between b and c Section. But at this time, the size of structure A is 8+2=10 bytes. According to rule 2, the size of structure A must be an integer multiple of its largest member type int, so fill 2 on the basis of 10 bytes. Bytes, to ensure that the final structure size is 12 to comply with rule 2.

 

Guess you like

Origin blog.csdn.net/m0_37981386/article/details/108329262