Structure Padding / Memory align

 As you know,  1 byte for char and 4 byte for int in 32-bit or 64-bit processor.

#include 

struct bag {
        char x;
        char y;
        int z;
};

struct employee {
        int id;
        char code;
};

int main() {
        struct bag b;
        struct employee e;
        printf("size of a struct bag is: %ld\n", sizeof(b));
        printf("size of a struct employ is: %ld\n", sizeof(e));
        return 0;
}

Here is the information about my research machine. (In 64-bit) 

Structure Padding / Memory align_第1张图片

Yeah, by the way, pay attention to the format of the value returned by sizeof().

Structure Padding / Memory align_第2张图片

Phenomenon about Padding

#include 

struct bag {
        char x;
        char y;
        int z;
};

struct employee {
        int id;
        char code;
};

​​struct box {
        char x;
        int z;
        char y;
};

int main() {
        struct bag b;
        struct employee e;
        printf("size of a struct bag is: %ld\n", sizeof(b));
        printf("size of a struct employ is: %ld\n", sizeof(e));
        struct box bx;
        printf("size of a struct box is: %ld\n", sizeof(bx));
        return 0;
}

Structure Padding / Memory align_第3张图片

Structure Padding / Memory align_第4张图片

Why is structure padding required?

The answer to that lies in how a CPU accesses memory. Typically a CPU has alignment constraints, e.g. a CPU will access one word at a time, or a CPU will require data to be 16byte aligned, etc. So to make sure that data is aligned according to the constraints of the CPU, padding is required. If data is not aligned it can either cause unaligned exceptions or the program will run slow as is explained by the following example. 

Structure padding increases memory consumption but is reduces CPU cycles. Structure contains structure members which can be accessed by a processor in chunks of 4 bytes at a time. Changing the order of variables inside will result in a change of output. 

 Frankly, I don't know the working principle of CPU, so I quote some sentences here.

Howrever, I will keep learning something about CPU, and I will turn back to explain the reasons on my own.

 

你可能感兴趣的:(开发语言,c语言)