Memory Alignment

I read the document recently and found that I don't quite understand the concept of memory alignment.
Principles of memory alignment:

  1. Data member alignment rules: For the data members of a struct (or union), the first data member is placed where the offset is 0, and the starting position of each data member in the future should be stored from the size of the member or the member The size of the sub-member (as long as the member has sub-members, such as arrays, structures, etc.) starts with an integer multiple of the size (for example, int is 4 bytes in a 32-bit machine, it must be stored from an integer multiple of 4 address.

  2. Structure as a member: If there are some structure members in a structure, the structure members should be stored from an integer multiple of the size of the largest internal element. (struct a contains struct b, b contains char, int, double and other elements, that b should be stored from an integer multiple of 8.)

  3. Finishing work: The total size of the structure, that is, the result of sizeof, must be an integer multiple of the largest member of the structure. If it is insufficient, it must be filled.

You can run the following code to verify:

#include<stdio.h>
typedef struct bb {
    int id;             //[0]....[3]
    double weight;      //[8].....[15]      原则1
    float height;      //[16]..[19],总长要为8的整数倍,补齐[20]...[23]     原则3
} BB;

typedef struct aa {
    char name[2];     //[0],[1]
    int id;         //[4]...[7]          原则1

    double score;     //[8]....[15]
    short grade;    //[16],[17]
    BB b;             //[24]......[47]          原则2
} AA;

int main() {
    AA a;
    printf("a = %d,b = %d",sizeof(a),sizeof(BB));
    return 0;
}

If you add #pragma pack(1) at the beginning, which means that it is aligned by one bit, that is, there is no memory alignment, you can run the experiment again.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325985331&siteId=291194637