sizeof of struct with bitfield members

In the latest draft of the language (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf) in '1.7 memory model' there is a struct with bitfield members.

Now, in a test program

#include <iostream>

struct S {
char a;
int b:5,
c:11,
:0,
d:8;
struct {int ee:8;} e;
};

int main(void) {

S s;

std::cout << sizeof(s) << std::endl;

return 0;

}

the output is 12 (64bit OS). Why is that? b and c are neighbors and will be placed in the same int, then d is placed in a different int (because of zero width bitfield) and nested structs are also placed in a different memory location. So I think sizeof must be 13 but I'm at a loss and would appreciate an explanation. Thanks!
Last edited on
based on what g++, clang++, intel, and oracle seem to agree to when compiling this struct (microsoft differs)

S.a takes the byte #1 (naturally)
S.b takes part of byte #2
S.c takes part of byte #2 and the whole byte #3
byte #4 is left unused because we're skipping to the next whole int (bytes 5,6,7,8)
S.d takes byte #5
bytes #6, #7, #8 are unused because we're skipping to the next whole int for member struct
S.e.ee takes byte #9
bytes #10, #11, #12 are unused (and belong to S.e whose sizeof is 4)

(microsoft inserts three more padding bytes after S.a, placing S.b at the start of an int boundary, and because of that it has to skip 2 bytes instead of 1 at :0, making the total sizeof 16)
Last edited on
@Cubbi Thank you for the explanation. So S.a is stored in the same int that contains the bits for S.b and S.c. That would explain why deleting S.a from the struct and then recompiling would give the same size as before. Initially I thought the size would be computed like so:

sizeof(S.a) = 1
sizeof(S.b and S.c) = 4
skip
sizeof(S.c) = 4
sizeof(S.e) = 4

giving a sum of 13.

I think the output of MSVC++ is more logical.

How could one look at the memory layout of the compiled binary?
Topic archived. No new replies allowed.