Memory map

Memory alignment principle

1. Data member alignment rules:

For struct (or union) data members, the first data member is placed at offset 0, and each data member is stored starting from the size of the member or the size of its children (as long as the member has children, such as arrays, Structure, etc.) (for example, if int is 4 bytes, it starts at the integer multiple address of 4.

2. Structure as a member:

If a struct has any struct members, the struct members should be stored from an address that is an integer multiple of the maximum internal element size.(Struct a contains struct b, and b contains char,int,double, etc., and b should be stored from an integer multiple of 8.)

3. Finishing work:

The total sizeof a structure, which is the result of sizeof,. Must be an integer multiple of its largest internal member. What is lacking must be made up.

The instance

struct LGStruct1 {
    double a;      //8byte should be in [0,7]
    char b;        //1 integer multiple of 1 [8]
    int c;         //4 9,10,11 is not an integer multiple of 4
    short d;       //2 16 is an integer multiple of 2 [16,17]
}struct1;          // According to the closing principle, take an integer multiple of 8 to get 24

struct LGStruct2 {
    double a;      //8byte should be in [0,7]
    int b;         //2 8 is an integer multiple of 2 [8, 9, 10, 11]
    char c;        //1 12 is an integer multiple of 1 [12]
    short d;       //2 13 is not an integer multiple of 2 [14,15]
}struct2;          // According to the closing principle, take an integer multiple of 8 to get 16

struct LGStruct3 {
    double a;              //8byte according to rule 1 [0,7]
    int b;                 //4 8 is a multiple of 4 [8, 9, 10, 11]
    char c;                //1 12 is an integer multiple of 1 [12]
    short d;               //2 13 is not an integer multiple of 2 [14,15]
    int e;                 //4 16 is an integer multiple of 4 [16, 17, 18, 19]
    struct LGStruct1 str;  // LGStruct1 has a maximum element of 8, so start with the integer bit of 8
                           // 20,21,22,23 is not an integer of 8, starting with 24
                           // for [24-31],[32][36 37 38 39][40 41] STR rounding to 47
}struct3;                  // Take 8 as an integer to get 48

NSLog(@"%lu-%lu",sizeof(struct1),sizeof(struct2));
NSLog(@"sizeof(struct3) = %lu",sizeof(struct3)); The output24-16
sizeof(struct3) = 48
Copy the code