Search code examples
c++structpacking

Why is this struct not the size I expect?


I am taking binary input from a file to a buffer vector then casting the pointer of that buffer to be my struct type.

The goal is for the data to populate the struct perfectly.

I know the size of all the various fields and the order they're going to come in.

As a result my struct needs to be tightly packed and be 42 bytes long. My issue is that it is coming out at 44 bytes long when I test it.

Also, the first value lines up. After that, the data is incorrect.

Here's the struct:

#pragma pack(push, 1)
struct myStruct
{
    uint8_t ID;
    uint32_t size: 24;
    uint16_t value;
    char name[12];
    char description[4];
    char shoppingList[14];
    char otherValue[6];
};
#pragma pack(pop)

Solution

  • Also, the first value lines up. After that, the data is incorrect.

    uint32_t size: 24;
    

    If you want to guarantee portably that this is three bytes with no padding before the next member, you're going to need to use a byte buffer and do the conversions yourself.

    #pragma pack is an extension, and the packing of bitfield members is anyway implementation-defined.

    FWIW both GCC and CLANG do seem to do what you want in this case, but unless it's defined by a platform ABI depending on this is still brittle.