Compare two unsigned char structures and bitfields

729 views Asked by At

I have a structure containing unsigned chars and bitfields:

struct {
unsigned char byt1    ;
unsigned char var1  :1;
unsigned char byt2    ;
unsigned char var2  :1;
unsigned char var3  :1;
unsigned char var4  :1:

} struct1;

I want to compare this struct with itself. I keep two copies of this struct and I want to just check if anything changed compared to first copy of it.

Is it safe to use memcmp() here? The real struct has 50+ members, and they are all unsigned chars or bits.

1

There are 1 answers

1
Some programmer dude On BEST ANSWER

The structure looks like it might contain lots of padding, and the contents of that memory is unspecified (see e.g. this old SO answer, and also this memcmp reference), so no you can't really use memcmp.

However, if you initialize the structures with e.g. memset then it should work. It's technically unspecified but in practice the memset should set the padding as well.

So to answer your question: If you always clear the structures using memset you should in practice be okay using memcmp, but in theory it's undefined behavior.