Force Specific Struct Size in C

情到浓时终转凉″ 提交于 2019-12-01 03:36:29

You can use a union.

struct mystruct_s {
    ... /* who knows how long */
};

typedef union {
    struct mystruct_s s;
    unsigned char padding[512];
} mystruct;

This will ensure the union is 512 bytes or more. Then, you can ensure that it is no more than 512 bytes using a static assertion somewhere in your code:

/* Causes a compiler error if sizeof(mystruct) != 512 */
char array[sizeof(mystruct) != 512 ? -1 : 1];

If you are using C11, there is a better way to do this. I don't know anybody who uses C11 yet. The standard was published a matter of weeks ago.

_Static_assert(sizeof(mystruct) == 512, "mystruct must be 512 bytes");

Note that the only way to pad with zeroes is to put the zeroes there manually (calloc or memset). The compiler ignores padding bytes.

I don't think that there's any way to automatize this, at least in gcc which is the compiler I use. You have to pad your structs.

Be careful about automatic alignment of variables in your struct. For example struct example{ char a; int b; }

does not take 5 bytes, but 8.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!