Force specific structure size in C

For various reasons, I have some structures that I want to force to specific sizes (in this case, 64 bytes and 512 bytes). And yet, they are lower than the sizes that I want them to be.

In any case, I need to tell the compiler to set them for these specific sizes and pads with zeros, or is it best for me to simply declare an array inside the structure that makes up the excess space so that it is aligned in size I want?

+6
source share
2 answers

You can use union.

struct mystruct_s { ... /* who knows how long */ }; typedef union { struct mystruct_s s; unsigned char padding[512]; } mystruct; 

This will provide a combination of 512 bytes or more. Then you can make sure that it is no more than 512 bytes using a static statement 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 anyone who uses C11 yet. The standard was published a few weeks ago.

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

Please note that the only way to fill with zeros is to set the zeros to manual ( calloc or memset ). The compiler ignores padding bytes.

+17
source

I don't think there is a way to automate this, at least in gcc, which I use for the compiler. You must fill out your structures.

Beware of automatically aligning variables in your structure. For example, struct example {char a; int b; }

does not accept 5 bytes, but 8.

0
source

Source: https://habr.com/ru/post/904943/


All Articles