Szymon Fortuna
Szymon Fortuna

Reputation: 400

sizeof(struct) different for different compilers

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?

Upvotes: 1

Views: 345

Answers (2)

user3415290
user3415290

Reputation: 45

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;

Upvotes: 0

ouah
ouah

Reputation: 145849

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.

Upvotes: 3

Related Questions