Memory alignment and usage of #pragma pack

Memory alignment related compilation preprocessing commands

#pragma pack(x): The value set by this instruction is recorded as x. When not set, x defaults to 8, which can override the definition, that is, execute

#pragma pack(1)
#pragma pack()

x is first set to 1, then to the default value of 8

memory alignment process

Assuming that the current header file defines a structure (struct, class, and union all follow memory alignment), consisting of char, int, and double (the order is important), if it is set, then x=4:

  1. Compare the number of bytes of the member double with the largest space in the structure with x, and take the smaller value as n, then n=4
  2. Compare n with the number of bytes of each member in the structure, and take the small value to get the array m[i], as follows:
    #pragma pack(4)
    struct Test {
          
          
        char ch;	// m[0] = sizeof(char) > n ? n : sizeof(char) = 1
        int num;	// m[1] = sizeof(int) > n ? n : sizeof(int) = 4
        double fnum;	// m[2] = sizeof(double) > n ? n : sizeof(double) = 4
    };
    
  3. Space is allocated according to the number of bytes of each member in the structure, but the difference between the start address of each member and the start address of the structure needs to be an integer multiple of the current m[i], as follows :
    insert image description here
  4. Finally, the number of bytes occupied by the structure needs to be an integer multiple of n, 16/4=4, that is, the size of the structure is 16 bytes. If it is not enough to divide n, expand the space occupied by the structure

example

#pragma pack()
class Test2 {
    
    
    char ch;	// m[0] = sizeof(char) > n ? n : sizeof(char) = 1
    double fnum;	// m[1] = sizeof(double) > n ? n : sizeof(double) = 8
    short snum;	// m[2] = sizeof(short) > n ? n : sizeof(short) = 2
};
  1. n=8
  2. Note as above
  3. The memory layout is as follows, the class size is 24 bytes
    insert image description here

Note: When n=1, there is no memory alignment restriction, and the size of the structure can be obtained by directly adding up each element.

Guess you like

Origin blog.csdn.net/m0_46324847/article/details/126614169