0

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.

zacharoni16
  • 305
  • 1
  • 4
  • 16
  • It is safe to use `memcmp` on bit-field structures just it it is safe to use `memcmp` on any other type of data (variables, arrays, "normal" structures, allocated statically or dynamically). Just as long as the `length` argument that you pass to `memcmp` does not make it exceed the ranges of either one of the input memory blocks, it should work correctly. – barak manos Jun 22 '15 at 15:12

1 Answers1

1

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.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621