【问题标题】:Why not byte padding taken place in this C program?为什么在这个 C 程序中不进行字节填充?
【发布时间】:2013-01-10 17:27:23
【问题描述】:

根据字节填充,在 32 位操作系统中,CPU 可以按此处给出的 4 的倍数寻址内存 when the computer's word size is 4 bytes (a byte meaning 8 bits), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. Even though the previous data structure ends at the 14th byte, the next data structure should start at the 16th byte. Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte.

#include<stdio.h>
struct test {
        char a;
        char b;
        int c;
        int d;
};
void main() {
        int a,b;
        char c,d;
        printf("Address of a & b = %u & %u respectively\n",&a,&b);
        printf("Address of c & d = %u & %u respectively\n",&c,&d);      
        struct test t1;
        printf("The size of structure:::%d\n",sizeof(t1));
}

输出是:

Address of a & b = 3216087804 & 3216087808 respectively
Address of c & d = 3216087802 & 3216087803 respectively
The size of structure:::12

当我以这种方式声明结构时:

struct test {
        char a;
        int b;
        int c;
        char d;
};

这种情况下的输出:

The size of structure:::16

为什么当我们尝试访问内存中奇数位置的secord char变量或地址为4的倍数时不存在的变量时不会发生对齐错误?

【问题讨论】:

    标签: padding


    【解决方案1】:

    在这两种情况下都进行了填充。在您提供的代码中,char b 不需要填充,因此不需要填充。 int c 需要两个字节的填充(我假设典型的 x86 规则)并得到它。结构体的总大小为 10 个字节的数据 + 2 个字节的填充,用于指示的 12 个字节。

    在单独的情况下,int b 需要三个字节的填充,而整个结构需要另外三个字节才能将char a 放在一个 4 字节的边界地址上。 10 字节的数据 + 3 + 3 字节的填充得到 16 字节。

    【讨论】:

    • 由于我的处理器无法寻址不是4的倍数,那么char b在内存中是如何访问的,应该会导致对齐错误?请纠正我。
    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多