user231536
user231536

Reputation: 2711

C++: sizeof of struct with bit fields

Why is gcc giving returning 13 as the sizeof of the following class ? It seems to me that we should get e (4 bytes) + d (4 bytes) + 1 byte (for a and b) = 9 bytes. If it was alignment, aren't most 32 bit systems aligned on 8 byte boundaries ?

class A {
  unsigned char a:1;
  unsigned char b:4;
  unsigned int d;
  A* e;
} __attribute__((__packed__));


int main( int argc, char *argv[] )
{
  cout << sizeof(A) << endl;
}

./a.out 13

Upvotes: 0

Views: 675

Answers (2)

Chetan Ahuja
Chetan Ahuja

Reputation: 941

You are very likely running on a 64 bit platform and the size of the pointer is not 4 but 8 bytes. Just do a sizeof on A * and print it out.

Upvotes: 12

K-ballo
K-ballo

Reputation: 81349

The actual size of structs with bitfields is implementation dependent, so whatever size gcc decides it to be would be right.

Upvotes: 6

Related Questions