结构的内存对齐

发布于 2025-01-04 17:55:23 字数 407 浏览 3 评论 0原文

我有一个包含三个字段的结构,定义如下:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
};

在使用 Intel sandybridge 处理器的 64 位系统上用 GCC 编译后,sizeof(tmp) 返回 24。

据我了解,编译器将 4 个字节填充到两个“unsigned int”字段。但是,如果没有填充并且生成的结构尺寸为 16,会不会更好?

想象一下,如果有一个此类结构体的数组,通过强制该结构体的大小为 16 将确保数组中没有单个结构体被缓存行分割,因为英特尔 SandyBridge 处理器的缓存行大小为 64 字节。因此,减少了在循环数组时进行两次内存访问来获取此类结构的机会。

I am having a struct with three fields defined as follows:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
};

After compiled with GCC on a 64-bit system using Intel sandybridge processor, the sizeof(tmp) returns 24.

To my understanding, the compiler pads 4 bytes to both "unsigned int" fields. However, could it be better if there is no padding and the resulting structure is of size 16?

Imagine if there is an array of such structs, by forcing the struct to have a size of 16 would make sure there is no single struct within the array being split over cache lines, since the cache line size is 64 bytes for Intel SandyBridge processors. Therefore reducing the chance to have two memory accesses to acquire such a struct when looping through the array.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叹倦 2025-01-11 17:55:23

我不明白为什么你的编译器会想要填充 unsigned int 成员,假设你没有一些奇怪的设置,其中 unsigned int 不是 32 位。在我的 GCC 上,我得到 sizeof(struct tmp) == 16

如果打印出每个成员的地址会发生什么?这应该可以帮助您找出填充的位置。但无论如何,您应该能够通过告诉 GCC 打包结构来消除填充,如下所示:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
} __attribute__((packed));

I don't see why your compiler would want to pad the unsigned int members, assuming you don't have some weird setup where unsigned int isn't 32-bit. On my GCC, I get sizeof(struct tmp) == 16.

What happens if you print out the address of each member? That should help you figure out where the padding is. But in any case, you should be able to get rid of the padding by telling GCC to pack the struct, like this:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
} __attribute__((packed));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文