64位系统差异的数据填充

时间:2012-09-25 13:02:01

标签: c struct sizeof

该程序使用指针(8个字节)和3个整数(每个4个字节)创建和测量结构,并显示有4个字节的数据填充。

我不明白为什么有4个字节的数据填充,要么CPU一次处理8个字节,应该有另外8个字节的填充,或者它一次处理4个字节,应该没有正确?

或者它是否在内存的8字节段中粘贴了2个4字节值,让CPU在运行时将其拆分? (这可以解释这种差异,但对我来说似乎有点低效)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test {
    char *name;
    int age;
    int height;
    int weight;
};

struct test *create(char *name, int age, int height, int weight)
{
    struct test *thing = malloc(sizeof(struct test));

    thing->name = strdup(name);
    thing->age = age;
    thing->height = height;
    thing->weight = weight;

    return thing;
}

void destroy(struct test *thing)
{
    free(thing->name);
    free(thing);
}


int main(int argc, char *argv[])
{
    struct test * t1 = create("bleh",1,2,3);

    printf("Sizeof struct: %lu\n",sizeof(struct test));
    printf("Sizeof pointer (On 64bit system): %lu\n",sizeof(char *));
    printf("Sizeof int: %lu\n",sizeof(int));

    destroy(t1);

    return 0;
}

输出:

Sizeof struct: 24
Sizeof pointer (On 64bit system): 8
Sizeof int: 4

2 个答案:

答案 0 :(得分:3)

出于对齐原因,整个结构可能在最后填充。这是必需的,因为您可能希望拥有此结构的数组。

你提到的填充使得结构总是以一个可被8整除的地址结束。

答案 1 :(得分:3)

指针可能需要在8个字节上对齐。想想当你形成一个班级数组test a[10]时会发生什么。确保a[i].name在8个字节上对齐的唯一方法是将类填充为8个字节的倍数。