Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why memcmp returns -1 although equal

I'm comparing using memcmp() two variables of the same struct (the struct has union in it). The variables are in two arrays and I'm running a loop where each iteration I do memcmp(&arr1[i], &arr2[i], sizeof(arrtype)).

When debugging I see that memcmp returns -1, but looking at the two variables and their values, I see that the variables has equal values. These arrays are zeroed with memset at the beginning.

  1. So does anybody know why memcmp returns -1 and not 0?
  2. Is there a better way to do what I need (compare two 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... */

/* get values into arr1, arr2 ... */


/* comparing both arrays in for loop*/
value = memcmp(&arr1[i], &arr2[i], sizeof(type0_t));
like image 360
theWizard Avatar asked Jul 07 '26 14:07

theWizard


1 Answers

You are likely reading indeterminate values (unitialized memory, or memory overwritten to contain unspecified data).

E.g. you could be accessing a member of a union that wasn't the member last written. Even if you don't, the last-written member might be smaller than the total extents of the union, leading to 'indeterminate' data beyond that 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 and b to compare equal bitwise because you never initialized all the bits in the first place (field2 has many more bits in excess of field1)

---Depending on the value of uninitialized memory also invokes Undefined Behaviour.--- Not true for C11

like image 149
sehe Avatar answered Jul 09 '26 08:07

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!