C语言结构体对齐的问题

做《操作系统》助教,给学生们提供一个实验的头文件时忽略了一个细节。

typedef struct dir_item {
    // the content of folders.
    // 128 bytes;
    uint8_t type;
    // 1 represents dir;
    uint32_t inode_id;
    uint16_t item_count;
    // 1 means the last one;
    // it doesn't matter if you don't understand it.
    char name[121];
} dir_item;

我给的注释是128字节,但这个大小是我口算的。一个学生发现了问题:这个结构体实际上占了132字节。这是因为结构体会自动按结构体里最大的元素去对齐,这里是32位。所以bytes浪费3个字节,item_count加两个char正好32位,但name剩下的119个char要占用30个32位,因此也浪费一个字节,共四个字节。
因此在我的代码里实际上是有风险的,而之前之所以没有出错是因为没有测试极端情况。如果name特别长达到120字节就会出错了,这个name就永远不会被找到。
但是改起来也好改,只需要调整一下顺序即可。

typedef struct dir_item {
    // the content of folders.
    // 128 bytes;
    uint32_t inode_id;
    uint16_t item_count;
    // 1 means the last one;
    // it doesn't matter if you don't understand it.
    uint8_t type;
    // 1 represents dir;
    char name[121];
} dir_item;

这提醒我万事还需小心、谨慎,假如我谨慎一点用sizeof看一下结构体大小就不会出这种问题了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值