C ++ memory alignment problem

In theory, under a 32-bit system, int occupies 4 bytes and char occupies one byte, then putting them in a structure should account for 4 + 1 = 5byte; but in fact, the result obtained by running the program is 8 byte, which is Caused by memory alignment. Look at the code as follows:

#include<stdio.h>
struct{
    int x;
    char y;
}s;

int main()
{
    printf("%d\n",sizeof(s);  // 输出8
    return 0;
}

The memory space in modern computers is divided by byte. In theory, it seems that access to any type of variable can start from any address, but the actual computer system has restrictions on the location of basic types of data stored in memory. They will The value of the first address of these data is required to be a multiple of a certain number k (usually it is 4 or 8), which is called memory alignment .

Each compiler on a specific platform has its own default "alignment factor" (also called alignment modulus). The default #pragma pack (4) in gcc can be changed by the pre-compiled command #pragma pack (n), n = 1,2,4,8,16.
Valid for its value: it is the smaller of the given value #pragma pack (n) and the length of the longest data type in the structure . The effective alignment value is also called the alignment unit

Personal understanding
Insert picture description here
The three pictures in the picture respectively represent the memory map of the X1, X2, X3 structure in the following code

#include<stdio.h>
struct
{
    int i;    
    char c1;  
    char c2;  
}x1;

struct{
    char c1;  
    int i;    
    char c2;  
}x2;

struct{
    char c1;  
    char c2; 
    int i;    
}x3;

int main()
{
    printf("%d\n",sizeof(x1));  // 输出8
    printf("%d\n",sizeof(x2));  // 输出12
    printf("%d\n",sizeof(x3));  // 输出8
    return 0;
}

For example, the memory of X1 and i is 4, which occupies the alignment unit 4, so the following C1, C2 will enter the next length of 4 units, and the memory length of C1 + C2 is less than 4, so the length of the X1 structure is 8 , And in X2, the memory length of the first element C1 is 1, the length of the second element is 4, 4 + 1 = 5, which exceeds the alignment unit, so i put the second memory unit, the third element put Go to the following memory unit, so the entire structure length is 8
refer to this article, the link is WeChat article

Published 9 original articles · liked 0 · visits 253

Guess you like

Origin blog.csdn.net/a_465240/article/details/104584289