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看一下结构体大小就不会出这种问题了。

发布了10 篇原创文章 · 获赞 0 · 访问量 449

猜你喜欢

转载自blog.csdn.net/dc199706/article/details/103537063