Sizeof not showing expected result

#include <stdint.h> #include <stdio.h> typedef union { uint64_t u[2]; struct { uint64_t a:30; uint64_t b:30; uint64_t c:30; uint64_t d:30; uint64_t e:8; }x; } mystruct; int main() { printf("Size %d\n", sizeof(mystruct)); } 

I am trying to compile it on a 64 bit machine. The expected result was 16, but I get 24. I know that alignment happened here, but I'm not sure why, since struct x is exactly 16 bytes. Can someone explain this. Thanks

+7
source share
3 answers

From standard C:

(C99, 6.7.2.1p10) "[...] If there is not enough space, will there be a bit field that does not fit, is placed in the next block or overlaps adjacent units from the implementation".

Thus, in your implementation, they do not overlap: members a and b are in one module, c and d are in another block, and e is in another unit: 8 + 8 + 8 = 24 .

+6
source

For a 64-bit machine, fields a and b use 60 bits of the first 64-bit value in the structure, c and d use 60 bits of the next 64-bit value in the struct, and then, since e is 8 bits, it cannot fit into 4 bits left over from this 64-bit value to require another 64-bit value. Thus, 8x3 = 24 bytes.

+6
source

An element of a bit field will never overlap two memory β€œunits” (in your case, a memory block is an element with 64 bits).

Besides the fact that the implementation of the bit field depends on the compiler, there is every chance that your bit field structure is actually stored in memory as follows:

 struct { uint64_t a:30; uint64_t b:30; uint64_t :4; uint64_t c:30; uint64_t d:30; uint64_t :4; uint64_t e:8; uint64_t :56; }x; 
+3
source

All Articles