内存对齐的原因是,包含类型 T 数组的结构体始终为 1。

huangapple go评论79阅读模式
英文:

Why memory alignment of structs that contain arrays of type T is always 1

问题

我在探讨内存对齐和填充问题,以为自己已经掌握了,直到遇到这个问题:

```cpp
struct Example {
   int x1; // 4
   char c; // 1 + 3 填充
   int x2; // 4
};

static_assert(sizeof Example == 12, "大小不正确");  // 正确

struct Example2 {
   long long x; // 8
   Example y;   // 12
                // 4 字节填充
};

static_assert(sizeof Example2 == 24, "大小不正确"); // 正确
    
struct Example3 {
   unsigned char x[8];     // 8
   unsigned char y[12];    // 12
                           // 4 字节填充??
};

static_assert(sizeof Example3 == 24, "大小不正确"); // 错误

我使用的是 64 位系统,使用 MSVC x64 编译器。为什么它总是将只包含数组类型的结构的内存对齐计算为 1?


<details>
<summary>英文:</summary>

I was exploring memory alignment and padding, and thought that I got the hang of it until I came across this:

```cpp
struct Example {
   int x1; // 4
   char c; // 1 + 3 padding
   int x2; // 4
};

static_assert(sizeof Example == 12, &quot;Incorrect size&quot;);  // OK

struct Example2 {
   long long x; // 8
   Example y;   // 12
                // 4 bytes padding
};

static_assert(sizeof Example2 == 24, &quot;Incorrect size&quot;); // OK
    
struct Example3 {
   unsigned char x[8];     // 8
   unsigned char y[12];    // 12
                           // 4 bytes padding??
};

static_assert(sizeof Example3 == 24, &quot;Incorrect size&quot;); // ERROR

I am on a 64-bit system, using MSVC x64 compiler. Why does it always calculate memory alignments for structs with only array types as 1?

答案1

得分: 1

long long x;需要8字节对齐,编译器会添加4字节填充以使Example2数组中的元素正确对齐。

unsigned char x[8];不需要任何对齐,Example3数组中的元素不需要对齐,因此编译器不会添加填充字节,但它可以添加,这取决于具体的实现。

英文:

long long x; requires the alignment 8, the compiler adds the 4 bytes padding to make elements in an array of Example2 properly aligned.

unsigned char x[8]; doesn't require any alignment, the elements in an array of Example3 do not need to be aligned, thus the compiler doesn't add padding bytes, but it can add them, it's implementation specific.

huangapple
  • 本文由 发表于 2023年6月22日 09:56:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定