0

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

2

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

3 Comments

This is correct, but I don't see any reason why it would allocate 5 bytes for 5 bits (unless its really stupid compiler without any internal bit-wise operations).
Yes, its a bit strange that it allocates an odd number of bytes. However, it can do it if it wants too, which is a strong hint that another method should be used in order to control the number of bytes allocated.
+1 - Right answer. If you want to be able to specify exactly which bytes get which data in a struct and what its ultimate size is, you'd be better off using Ada.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.