gpt4 book ai didi

c - 为什么结构中的 double 成员未在 8 字节边界上对齐?

转载 作者:太空狗 更新时间:2023-10-29 14:56:28 26 4
gpt4 key购买 nike

这是关于内存对齐的。在下面的代码中,我预计结构中 b 的偏移量为 8(32 位机器)。参见 here .从而使 b 始终出现在缓存行中。然而,事实并非如此。 struct test1 的全局对象中的成员 b 似乎是对齐的。我不确定是偶然还是编译器故意这样做。

我想了解为什么编译器不在 a 之后填充 4 个字节。

struct test1
{
int a;
double b;
}t1;

int main()
{
struct test1 *p = malloc(sizeof(struct test1));
printf("sizes int %d, float %d, double %d, long double %d\n", sizeof(int), sizeof(float), sizeof(double), sizeof(long double));
printf("offset of b %d\n",(int)&(t1.b)-(int)&(t1));

printf("\naddress of b (on heap) = %p, addr of b (on data seg) = %p\n",&(p->b), &(t1.b));

return 0;
}

输出是...

sizes int 4, float 4, double 8, long double 12
offset of b 4

address of b (on heap) = 0x804a07c, addr of b (on data seg) = 0x80497e0

我在 ubuntu 10.04 上使用标准的 gcc 编译器

最佳答案

根据System V ABI for i386 ,第 28 页,double 仅获得 4 字节对齐,但建议编译器也提供 8 字节的选项。这似乎是 GCC 在 Linux 上实现的,该选项称为 -malign-double

另一种选择是使用 -m64 来获取 x86-64 目标代码,这在包括 Mac OS X 在内的某些系统上已经是默认设置。

关于c - 为什么结构中的 double 成员未在 8 字节边界上对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com