Search code examples
c++structurepaddingsizeofmemory-alignment

Why g++ isn't performing structure packing here?


Consider following program:

#include <iostream>
struct __attribute__((__packed__)) mystruct_A
{
   char a;
   int b;
   char c;
}x;
int main()
{
    std::cout<<sizeof(x)<<'\n';
}

From this I understood following:

  • Structure packing suppresses structure padding, padding used when alignment matters most, packing used when space matters most.
  • Structure Packing, on the other hand prevents compiler from doing padding

I am on 32 bit environment & using Windows 7 OS. The 1st answer of linked question says that above code would produce structure of size 6 on a 32-bit architecture.

But when I compiled it using g++ 4.8.1 it gives me 9 as an output. So, is structure packing not happening completely here? Why extra 3 bytes are there in output? sizeof char is always 1. Sizeof int is 4 on my compiler. So, sizeof above struct should be 1+4+1=6 when structure is packed.

I tried it on here. It gives me expected output 6.

Is there any role of processor or it depends only on Compiler?


Solution

  • attribute packed is broken on mingw32 compilers. Another option is to use pragma pack:

    #pragma pack(1)
    struct mystruct_A {
      char a;
      int b;
      char c;
    } x;