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.
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 usememcmp
.However, if you initialize the structures with e.g.
memset
then it should work. It's technically unspecified but in practice thememset
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 usingmemcmp
, but in theory it's undefined behavior.