1

Supposing I have a code like this:

#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
    typedef struct{
        uint16_t x : 9;
        uint8_t y : 7;
    } z;
    printf("sizeof(z) = %lu\n",sizeof(z));
}

I have different results for clang on Mac (2) and someone told me on Windows it returned (3). Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?

Szymon Fortuna
  • 400
  • 1
  • 11
  • advise *what?* what do you want? why would you worry? of course different compilers on different platforms do different things when it comes to implementation details… – The Paramagnetic Croissant Feb 18 '15 at 09:48
  • 1
    Read this http://stackoverflow.com/questions/18284640/c-size-of-structure-when-bit-field-is-used-and-how-it-is-stored-in-memory – Matt Feb 18 '15 at 09:49
  • Unless you insert unnamed, zero-size bitfields, you can't assume anything about the layout of the bitfield. – Kerrek SB Feb 18 '15 at 09:51
  • Advice: If memory layout or size is important, don't use bit-field because practically nothing is guaranteed. – user694733 Feb 18 '15 at 09:54
  • 1
    You can get them packed to 2 bytes on Windows by making them both uint16_t. – Hans Passant Feb 18 '15 at 09:58

2 Answers2

3

Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?

The first thing to remember about bit-field is this phrase from K&R, 2nd:

(6.9 Bit-fields) "Almost everything about fields is implementation-dependent."

It includes padding, alignment and bit endianness.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

There are two possible problems that might be occurring:

Bit-fields are very poorly standardized part within the ANSI C specification. The compiler chooses how bits are allocated within the bit-field container.You should avoid using them inside structures instead you can use #define or enum.

The second possible issue is that the compiler will lay the structure in memory by adding padding to ensure that the next object is aligned to the size of that object.It is a good practices to place elements of the struct according to their size:

typedef struct{
        uint8_t x : 7;
        uint16_t y : 9;
    } z;
user3415290
  • 45
  • 1
  • 6