sizeof()在32位和64位进程之间表现不同

时间:2017-06-21 12:06:15

标签: c++ g++

考虑以下计划

#include<iostream>

struct SimpleStructure
{
    double obj;
};

struct Composite
{
    struct SimpleStructure u;
    char ch;
};

int main()
{
    using namespace std;

    cout << "sizeof(double)                 : " << sizeof(double) << endl;
    cout << "sizeof(struct SimpleStructure) : " << sizeof(struct SimpleStructure) << endl;
    cout << "sizeof(struct Composite)       : " << sizeof(struct Composite) << endl;
    return 0;
}

当我用g++ -m64 <filename>.cpp编译上面的内容时,我得到以下输出

sizeof(double)                 : 8
sizeof(struct SimpleStructure) : 8
sizeof(struct Composite)       : 16

但是当我使用g++ -m32 <filename>.cpp编译时,相同的代码,我得到以下输出

sizeof(double)                 : 8
sizeof(struct SimpleStructure) : 8
sizeof(struct Composite)       : 12

为什么32位和64位进程中的结构填充有差异?

3 个答案:

答案 0 :(得分:1)

在32位平台alignof(double) == 4上。见man gcc

  -malign-double
  -mno-align-double
       Control whether GCC aligns "double", "long double", and "long long"
       variables on a two-word boundary or a one-word boundary.  Aligning
       "double" variables on a two-word boundary produces code that runs
       somewhat faster on a Pentium at the expense of more memory.
       On x86-64, -malign-double is enabled by default.

      Warning: if you use the -malign-double switch, structures
       containing the above types are aligned differently than the
       published application binary interface specifications for the
       x86-32 and are not binary compatible with structures in code
       compiled without that switch.

结构的大小是具有最大对齐要求的成员对齐的倍数。此处,此类成员的类型为double,因此sizeof(struct Composite) == N * alignof(double)

答案 1 :(得分:0)

就C标准而言,编译器可以自由选择任何对齐方式。以下是关于我使用的编译器如何实现对齐的描述。

通常,选择字长(32位系统为32位,64位系统为64位),因为就目标平台上的内存使用和性能之间的权衡而言,它通常是一种有效的选择。通常可以在字大小的块中访问存储器,并且cpu指令假定数据是对齐的,因此如果数据未对齐,则cpu将需要访问2块存储器并将数据移位到对齐。这浪费了宝贵的cpu周期。

小于字大小的实体按其大小对齐。字大小和更大的实体在字边界上对齐。

结构成员分别对齐,然后填充整个结构并与其最大成员对齐。

通常可以使用pragma覆盖默认对齐方式。有关详细信息,请参阅编译器的文档。

示例:

/* Override the default alignment and pack everything tight. */
#pragma pack(1)

答案 2 :(得分:-1)

首先,整数类型的大小可能因架构而异。这里有一张很好的表格:http://en.cppreference.com/w/cpp/language/types

其次,指针具有不同的大小,具体取决于体系结构。 32位机器有32位指针,64位机器有64位指针。如果你对旧架构感兴趣,8位机器有16位指针,16位机器有32位指针,尽管它们在8086上很奇怪。

最后,你的结构中的情况可能是对齐的。出于效率原因,变量与字边界对齐,字体大小可能因架构而异。请在此处查看更多信息:http://en.cppreference.com/w/cpp/language/object#Alignment