包结构/避免填充 [英] pack struct / avoid padding

查看:117
本文介绍了包结构/避免填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

  struct SkipListNode {
void * data; // 8字节
uint8_t size; // 1字节
// 7字节在这里填充...
void * next [1]; //动态数组,每个8字节cell
};

我使用 malloc()和I我分配的空间大于 sizeof(SkipListNode),所以我扩展了 next [] 数组。



我想避免 7字节浪费。我可以完全删除大小字段,但是我应该在数组的末尾保留单个 NULL (8个字节)。然而,这并没有帮助减小尺寸。



我应该使用 __属性__((__ packed __))或者那里一些不同的方式我可以做到这一点?

这必须在C和C ++下编译。



编译器是gcc。

解决方案

  #include< stdio.h> 
#include< stdint.h>

struct SkipListNode {
void * data; // 8字节
uint8_t size; // 1字节
void * next [1];
};

struct SkipListNode_pack {
void * data; // 8字节
uint8_t size; // 1字节
void * next [1];
} __attribute __((packed));

int main(int argc,char ** argv)
{
printf(%d:%d \ n,sizeof(struct SkipListNode),sizeof(struct SkipListNode_pack));
返回0;
}

以上代码的输出:

ishaypeled @ arania sandbox] $ ./test


24:17



所以是的,如果你想节省内存的话,你应该肯定使用 __ attribute __((packed))。另一方面,就像@MarioTheSpoon说的那样 - 它可能会带来性能损失。

我会检查填充解决方案,看看您是否可以在特定机器上承受这种损失。我敢打赌,除非你真的关键,否则你甚至不会注意到它。


I have following struct:

struct SkipListNode{
    void        *data;      // 8 bytes
    uint8_t     size;       // 1 byte
    // 7 bytes padding here...
    void        *next[1];   // dynamic array, 8 bytes each "cell"
};

I am using malloc() and I am allocating more space than sizeof(SkipListNode), so I am extending the next[] array.

I want to avoid 7 bytes waste. I can completely remove size field, but then I should keep single NULL (8 bytes) at the end of the array. However this does not help reducing the size.

Shall I use __ attribute__((__ packed__)) or there some different way I could do the trick?

This must be compiled under C and C++ as well.

Compiler is gcc.

解决方案

#include <stdio.h>
#include <stdint.h>

struct SkipListNode{
    void        *data;      // 8 bytes
    uint8_t     size;       // 1 byte
    void *next[1];
    };

struct SkipListNode_pack{
    void        *data;      // 8 bytes
    uint8_t     size;       // 1 byte
    void *next[1];
    } __attribute__((packed));

int main(int argc, char** argv)
{
    printf("%d:%d\n", sizeof(struct SkipListNode), sizeof(struct SkipListNode_pack));
    return 0;
}

The output from the above code:
ishaypeled@arania sandbox]$ ./test
24:17

So yeah, you should definitely use __attribute__((packed)) in your case if you want to save memory. On the other hand, like @MarioTheSpoon states - it may come with a performance penalty.

I'd check the padding solution to see if you can live with that penalty on your specific machines. My bet is you won't even notice it unless you're really performance critical.

这篇关于包结构/避免填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆