Search code examples
cstruct8-bit

Size-of struct with uneven 8bit members is not uneven


Good evening!

'Got the following problem: I have an input stream of multi- and single-byte datatypes and just want to lay it over a struct. Unfortunately, if I put an uneven amount of 8bit members in a struct together with 16bit members, the sizeof() function will give me the round up to an even length.

Following example:

Datatypes:

struct uuu { // should contain 5 bytes
    uint8_t a[1];
    uint8_t b[1];
    uint16_t c;
    char d[1];
};
struct ccc { // should contain 5 bytes
    char a;
    char b;
    char c;
    uint16_t d;
};
struct bbb { // should contain 3 bytes
    char a;
    char b;
    char c;
};

Snippet:

printf("char_bit: %d\n", CHAR_BIT);
printf("%d | %d | %d", sizeof(uuu), sizeof(ccc), sizeof(bbb));

Result:

char_bit: 8
6 | 6 | 3

The point is, I need an exact order of 8bit member to parse the stream into the predefined struct. Is there a way to force this? Working on a 64bit machine, tried already compiling with the -m32 gcc flag.

I know it has to do with paddings of struct etc. But is there a workaround to still achieve the fixed structure sizes?

Thanks in advance!


Solution

  • If you use the packed attribute, your structs will not contain padding.

    struct __attribute__((packed)) uuu { // will now contain 5 bytes