为什么在结构双重成员不能在8字节边界上对齐? [英] Why is a double member in struct not aligned on 8 byte boundary?

查看:109
本文介绍了为什么在结构双重成员不能在8字节边界上对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于内存对齐。在下面code,我希望B的结构内部的偏移量为8(32位机)。请参见这里。那里,使 B 总是发生在一个高速缓存行。然而,事实并非如此。在结构测试1 的全局对象的成员 B 似乎一致。我不知道如果是偶然或编译器是这样做的故意。

This is about memory alignment. In code below, I expected that the offset of b inside the structure to be 8 (32-bit machine). See here. There by, making b always occur within a cache line. However, that's not the case. The member b in a global object of struct test1 seems to be aligned. I am not sure if its by chance or compiler is doing this deliberately.

我想明白为什么编译器是不是在填充4个字节的

I wanted to understand why compiler is not padding 4 bytes after a.

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;
}

输出结果是...

The output is...

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

我是用标准的gcc编译器在Ubuntu 10.04

I am using standard gcc compiler on ubuntu 10.04

推荐答案

按照系统V ABI i386的,第28页,只得到4个字节对齐,但是编译器被推荐为8字节提供一个选项,也是如此。看来这就是由GCC在Linux上实现,被称为选项 -malign双

According to the System V ABI for i386, page 28, double only gets 4 bytes alignment, but compilers are recommended to provide an option for 8 bytes as well. It appears this is what is implemented by GCC on Linux, the option being called -malign-double.

另一种方法是使用 -m64 来获得x86-64的对象code,这已经在一些系统上,包括Mac OS X的缺省值。

Another alternative is to use -m64 to get x86-64 object code, which is already the default on some systems including Mac OS X.

这篇关于为什么在结构双重成员不能在8字节边界上对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆