4

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?

Community
  • 1
  • 1
Destructor
  • 14,123
  • 11
  • 61
  • 126

2 Answers2

4

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;
0

Solution here worked for me: https://wintermade.it/blog/posts/__attribute__packed-on-windows-is-ignored-with-mingw.html, which is to add -mno-ms-bitfields to the compiler flags.

Ayberk Özgür
  • 4,986
  • 4
  • 38
  • 58