Structure Padding / Memory align

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

#include <stdio.h>

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) 

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

Phenomenon about Padding

#include <stdio.h>

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;
}

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.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值