-1

I have this struct in C:

typedef struct Set {
    unsigned int state : 1;
    char array[LEN];
} Set;

While this compiles and executes I noticed that the bit-field actually alters one bit in the char array itself! So it I'm wondering if this is some known issue and it is bad practice to have bit-fields with other data types in one struct or I'm not doing something correctly.

Yos
  • 1,276
  • 1
  • 20
  • 40
  • 4
    Do you have a complete program which shows the char array being altered because of the bitfield? I fail to believe. – DeiDei Dec 23 '16 at 10:08
  • [Minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) is needed. – user3386109 Dec 23 '16 at 10:15
  • the code is too large to post it here and there're a lot of functions who work on the struct. I did notice that if I replace the bit-field with a field of type char everything works normal. I just wanted to quickly ask if using bit-fields with fields of other data type is OK. – Yos Dec 23 '16 at 10:26
  • 2
    *"I just wanted to quickly ask if using bit-fields with fields of other data type is OK."* Yes, changing the bitfield to a `char` moves stuff around in memory, so your bug doesn't have the same effect. The point of a MCVE is that you'll prove to yourself that you can't recreate the bug with a simple example. Hence, the bug has nothing to do with what you've asked in the question. Or, if you can reproduce the bug with a simple example, then you should post it so that we can take a look. – user3386109 Dec 23 '16 at 10:31

1 Answers1

3

Hogwash!

Rest assured that elements of a struct are always laid out so they are disjoint in memory.

You program clearly has a construct that is causing undefined behaviour - most likely you are indexing array[-1] or similar.

(Unless some smart alec has written #define struct union: the behaviour of that is also undefined since you shouldn't redefine a keyword in C.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483