c - GCC 为什么会生成错误的结构偏移量?

标签 c gcc

我有这个代码:

mbr.h:

struct mbr_partition {
                char flags;
                char start_head;
                char start_sector;
                char start_cyl;
                char type;
                char last_head;
                char last_sector;
                char last_cyl;
                uint32_t start;
                uint32_t size;
        };

        struct mbr {
                char bootloader[446];
                struct mbr_partition partition1;
                struct mbr_partition partition2;
                struct mbr_partition partition3;
                struct mbr_partition partition4;
                char magic[2];
        };

和:main.c:

int main()
{
        printf("%d\n", sizeof(struct mbr));
        printf("%d\n", sizeof(struct mbr_partition));
        printf("%d\n", sizeof(long));
        struct mbr mbr;
        printf("%d, %d\n", ((char *) &mbr.magic) - ((char *) &mbr), sizeof(mbr)$
        printf("1: %d\n", ((char *) &mbr.partition1) - ((char *) &mbr));
        printf("2: %d\n", ((char *) &mbr.partition2) - ((char *) &mbr));
        printf("3: %d\n", ((char *) &mbr.partition3) - ((char *) &mbr));
        printf("4: %d\n", ((char *) &mbr.partition4) - ((char *) &mbr));
        return 0;
}

并输出:

516
16
8
512, 516
1: 448
2: 464
3: 480
4: 496

为什么size是516字节(应该是512)? 为什么 partition1 偏移量是 448 而不是 446? 我该如何解决?

最佳答案

因为可能会有一些填充字节或填充位。

引自 N1570 6.7.2.1 结构和 union 说明符:(强调我的)

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

关于c - GCC 为什么会生成错误的结构偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376426/

相关文章:

c - 混合使用 mmap(2) 和 malloc(3) 的安全方法需要 : the result of mmap(2) must be continuous

c - C 中链表的逻辑错误

java - 通过UDP解码java中的C结构数据报包

c - C 中的分段 11

gcc - 检查 Makefile 中的 gcc 版本?

gcc - 使用 GCC 的 -Wpointer-arith

c - 在c中定义函数和打印

c++ - 条件变量等待抛出异常

c - 这是什么意思,我该如何纠正它 *** 检测到堆栈粉碎 *** : ./array1output 终止

gcc ld : symbol(s) not found for architecture x86_64