i'm comparing using memcmp()
2 variables of same struct (the struct has union in it). variables in 2 arrays , i'm running loop each iteration memcmp(&arr1[i], &arr2[i], sizeof(arrtype))
.
when debugging see memcmp returns -1, looking @ 2 variables , values, see variables has equal values. these arrays zeroed memset @ beginning.
- so know why
memcmp
returns -1 , not 0? - is there better way need (compare 2 memory blocks)?
code:
typedef struct type1 { int version; union { option1_t opt1; option2_t opt2; } union_t; } type1_t; typedef struct type0 { type1_t member1; type2_t member2; type3_t member3; type4_t member4; type5_t member; } type0_t; type0_t arr1[size]; type0_t arr2[size]; memset(arr1, 0, size * sizeof(type0_t)); memset(arr2, 0, size * sizeof(type0_t)); /* doing irrelevant stuff... */ /* values arr1, arr2 ... */ /* comparing both arrays in loop*/ value = memcmp(&arr1[i], &arr2[i], sizeof(type0_t));
you reading indeterminate values (unitialized memory, or memory overwritten contain unspecified data).
e.g. accessing member of union wasn't member last written. if don't, last-written member might smaller total extents of union, leading 'indeterminate' data beyond size.
struct x { union { char field1; long long field2[10]; }; }; struct x a,b; a.field1 = 'a'; b.field1 = 'a';
you can't expect a
, b
compare equal bitwise because never initialized bits in first place (field2
has many more bits in excess of field1
)
---depending on value of uninitialized memory invokes undefined behaviour.--- not true c11
Comments
Post a Comment