What is memory alignment

Before we talk about memory alignment, let’s look at an example:

struct Struct1{
    double a;
    char b;
    int c;
    short d;
    }struct1;

struct Struct2{
    double a;
    int b;
    char c;
    short d;
}struct2;

printf("struct1Size:%lu---struct2Size:%lu",sizeof(struct1),sizeof(struct2));

Copy the code

The following figure shows the size of each type in bytes in C and OC

Struct1 = 8+1+4+2=15, struct2 = 8+4+1+2=15, struct1 = 8+4+1+2=15 Just adjust the order of structure members, but there are two different results? So that’s the memory alignment principle.

Memory alignment principles

1, Data member alignment rules: the first data member of a struct (or union) is placed at offset 0, and the starting position of each data member is from the size of the member or the size of the member’s children (as long as the member has child members, such as arrays). Structure, etc.) (for example, if int is 4 bytes, it is stored from the address that is a multiple of 4.

2, Struct as members: If a struct contains members, then the members are stored at multiples of the size of the largest element in the struct.

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

Struct1, struct2, struct1, struct2, struct1, struct2

According to the first principle of memory alignment, the first member is stored at offset 0. The size of the int type of struct1 is 4 bytes, which should be stored at a multiple of 4. The size of the char is 1, and the subsequent positions 9, 10, and 11 are not divisible by 4. The size of the structure should be divisible by the size of the largest double (8) according to the third principle of memory alignment, the size of the structure should be divisible by the size of the largest double (8), which needs to be filled up to 24, so the size of the struct1 is 24. Similarly, the int and char positions of struct2 can be divisible by the size of the type, while the size of short is 2 bytes and needs to be stored from the 14th position. According to the third principle, the current size of 16 is divisible by the size of double, and the final size of struct2 is 16.

Second principle:

struct Struct3 {
    double a;
    int b;
    char c;
    short d;
    int e;
    struct Struct1 str;
}struct3;
Copy the code

If structure contains structure members, according to the principle of memory alignment of the second largest members from its internal structure element size began to store the integer times of address, namely struct1 storage location is from the members of his biggest is divisible by the size of the current position should be divided exactly by 8, storage location to begin from 24th, Struct1 = 24; struct3 = 48;