Memory alignment -> Personal interview understanding

Data is placed in the memory according to a certain order, but the data types occupy bytes of different sizes, so the "memory alignment" method is used to divide the address. Its function is to standardize the storage address of the memory in the space, which is very important for searching.

for example:

struct k {
    char a;
    double b;
    char c;
    int d;
};

Take this structure, char is 1b, double 8b, and int 4b. If the direct calculation is 14 bytes, it is found in the memory-aligned calculation that the maximum is 8 bytes at the beginning (double, if the first 4 bytes of int can be divisible by 8, it can be replaced), so it is

1(+7)+8+1+4(+3) is calculated to be 24 bytes, but it is very difficult for us to find it, because this is just one of the examples, but if I change the order, it will be different, so certain specifications are needed to give the address addressing rules to follow, there is memory alignment, do not confuse it with byte alignment .

What is byte alignment

Byte alignment: The computer storage system stores data in units of Bytes, and different data types occupy different spaces, such as: integer (int) data occupies 4 bytes, character (char) data occupies one byte, short integer (short) data occupies two bytes, and so on. In order to quickly read and write data, the computer stores data at the starting position of a certain address by default. For example, integer data (int) is stored at the starting position whose address is divisible by 4 by default, character data (char) can be stored at any address position (divisible by 1), and short integer (short) data is stored at the starting position whose address is divisible by 2. This is the default byte alignment.

What is memory alignment for

The place where memory alignment is implemented is generally a structure such as a structure or a union where an object contains multiple member variables. You can refer to the previously written article .

How to perform memory alignment

The alignment method is mainly based on the alignment coefficient. First, it can be changed according to the pre-compilation command, but if it is not set, the widest data type will be used as the alignment coefficient, and the rest of the data members will be stored according to the alignment coefficient. If the sum exceeds this coefficient, it will need to go to the next standard address space, and the remaining vacant address will be filled by the compiler. These bytes are generally meaningless data, which are only used to facilitate addressing and prevent errors when searching .

Guess you like

Origin blog.csdn.net/hoxidohanabi/article/details/128066078