5

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?

Gul Ershad
  • 1,743
  • 2
  • 25
  • 32
KcFnMi
  • 5,516
  • 10
  • 62
  • 136

2 Answers2

4

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).

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 1
    That's what I thought it had to do with the OS because on my Linux system it didn't happen. And that was why [I suggested what's in my comment](http://stackoverflow.com/questions/31480287/troubles-while-reading-the-struct-size?noredirect=1#comment50926597_31480287) which you can append to this answer if you like. – Iharob Al Asimi Jul 17 '15 at 16:48
0

It is clearly an alignement problem, meaning it has nothing to do with the language itself but all with the underlying platform.

If the platform knows (or thinks) that int32_t need an alignement of 4, it should add 3 bytes of padding after time.

Anyway __attribute__((__packed__)) is non standard C and will only be interpreted by gcc (*). Worse it leads to non portable programs : according to this answer on another question, it would cause a bus error on a Sparc architecture because of a misaligned int32_t.

I do know that x86 (and derivatives) architecture are now the most common, but other architecture may still exist ...

(*) according to Visual C++ equivalent of GCC's __attribute__ ((__packed__)), the MSVC equivalent is #pragma pack(push, 1)

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252