c - 为什么内存对齐会在结构内发生变化?

标签 c windows visual-studio-2012 memory alignment

previous question 中, 我 learned当一个具有 8 字节对齐的结构嵌入另一个具有 4 字节对齐的结构时,需要在 8 字节对齐的结构之前进行填充。

明白了。

至少我认为我理解了。

VS 2012 docs说:

For structures, unions, and arrays, the alignment-requirement is the largest alignment-requirement of its members.

所以,如果我有这样的结构:

typedef struct s_inner {
  unsigned long ul1;
  double        dbl1;
  fourth_struct s4;
  unsigned long ul2;
  int           i1;
} t_inner;

我希望这个结构的所有成员都是 8 字节对齐的,因为 double 是 8 字节对齐的。

但是我的内存转储显示了这个:

memdump

t_inner 从地址 1B8 开始:

  • 1B8:unsigned long 被填充,因为该结构是 8 字节对齐的
  • 1C0:double 占用 8 个字节
  • 1C8:后面是fourth_struct它有4字节对齐

到现在为止,一切都如期而至。但是现在 t_inner 中的对齐切换: 在地址 1E8 上,我希望在这里找到 unsigned long,用 4 个字节填充,以便下面的 int 也对齐8 个字节。但似乎对齐已经改变,因为 unsigned long 携带填充字节。相反,以下 int 以 4 字节对齐方式放置。

为什么对齐方式会在 t_inner 内切换?这里应用了哪条规则?

最佳答案

I'd expect all members of this structure would be 8-byte aligned since the double is 8-byte > aligned.

嗯,不。每个类型在结构内部都有自己的对齐方式,结构本身有一个最大的对齐方式它的内容对齐方式。

aligned.    typedef struct s_inner {
      unsigned long ul1;        // 4-aligned
      double        dbl1;       // 8-aligned  (need 4 padding before this)
      fourth_struct s4;         // 4 aligned  size 32
      unsigned long ul2;        // 4 aligned  (no padding)
      int           i1;         // 4 aligned  (no padding)
      // no padding needed as struct is a multiple of 8 bytes
    } t_inner; 

由于 double ,结构本身对齐 8。

关于c - 为什么内存对齐会在结构内发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27858493/

相关文章:

visual-studio-2010 - 在 Visual Studio 2012 中编译 Moles 时出现错误 "The type or namespace xxxx does not exist"

c# - 使用单击一次部署时的安装问题

c++ - 将指针数组初始化为 NULL

c - 从用户输入的数组中删除空格

c - 解析 IP header 时出错

windows - 如何在 git clone 之后修复 Windows 行结尾

c# - Monogame 模板在启动时崩溃并出现 System.TypeInitializationException

C# Forms Picturebox 以显示纯色而不是图像

c++ - 如何在 C++ 中使用 Microsoft Visual Studio 2012 查找语法错误?

c - 为什么无缓冲的 read()/write() 操作使用缓冲区缓存?