x86_64堆栈对齐-多余字节的用途

时间:2018-12-15 21:36:22

标签: c++ gcc x86-64 memory-alignment abi

最近,我正在学习有关内存对齐和相关问题的知识,这使我找到了以下程序:

#include <cstdio>
#include <cstdint>


struct XX
{
    uint8_t a;
    uint32_t b;
    uint16_t d;
    uint64_t c;
};

int main()
{
     printf("\n\ntype size: %zu\n", sizeof(XX));

     XX one;
     XX two;
     XX three;
     printf("addresses of one-three:\n\t%p\n\t%p\n\t%p\n", reinterpret_cast<void *>(&one), reinterpret_cast<void *>(&two), reinterpret_cast<void *>(&three));
     printf("\ndifference of addresses between one and two: %lu\n", reinterpret_cast<unsigned long>(&one) - reinterpret_cast<unsigned long>(&two));
     printf("difference of addresses between two and three: %lu\n", reinterpret_cast<unsigned long>(&two) - reinterpret_cast<unsigned long>(&three));
     printf("alignment of type alone: %zu\n", alignof(XX));

     XX arr[2];
     printf("\ndifference of addresses in array: %lu\n", reinterpret_cast<unsigned long>(&arr[1]) - reinterpret_cast<unsigned long>(&arr[0]));
     printf("alignment of array type: %zu\n", alignof(XX[]));
}

我使用GCC 8.1.0将其编译为:

  

g ++ -std = c ++ 17 -O0 main.cpp

输出说:

  • 对齐方式是8个字节,
  • 大小为24个字节,
  • XX 实例在数组内部的差异为24个字节(连续的内存,这并不奇怪),但作为独立变量的差异为32个字节

为什么独立变量之间的字节数超过8个?

0 个答案:

没有答案