Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles while reading the struct size

Tags:

c

If I debug the following code then I see the size value is 12 (as expected).

#include <cstdint>

int main(int argc, char *argv[])
{
    typedef struct __attribute__((__packed__))  { int8_t value; } time;

    typedef struct __attribute__((__packed__))  {
        uint8_t msg[8];
//        time t1;
        uint32_t count;
    } theStruct;

    theStruct s;
    int size = sizeof(s);

    return 0;
}

Interestingly, removing the comment at "time t1;", the value of size goes to 16. I was expecting 13.

I know (more or less) that this is explained by the data structure padding story...

But, is there some way to avoid this issue? What to do in order to read size = 13?

like image 867
KcFnMi Avatar asked Sep 28 '22 07:09

KcFnMi


1 Answers

There are some issues with MinGW's emulation of MSVC struct packing.

The workaround is to pass -mno-ms-bitfields flag to the compiler; this will cause it to use its own layout algorithm rather than attempt to emulate MSVC.

See also Struct packing and alignment with mingw (ARM but may be the same issue).

like image 51
ecatmur Avatar answered Oct 16 '22 19:10

ecatmur