XOR identical data in C leads to nonzero value. Why?

  • A+

How can I xor two data segments pointed by pointers?

I've tried this, one based on a similar solution on stackoverflow, but the output is not what I expected.

Here is the code:

void printXor(){         int j;     char* c = strdup("hey");     for(j = 0; j < strlen(c); j++){         c[j] ^= c[j];     }      printf("%d/n", *(int*)(c)); } 

But the output is: 7955712. Shouldn't the output be 0? I'm xoring "hey" over "hey" and its value in int is 0 right?


Take a look at this loop:

for(j = 0; j < strlen(c); j++) {     c[j] ^= c[j]; } 

You are modifying c and calculating its length using strlen. After the first iterator strlen returns 0 and loop stops.

If you translate 7955712 to hex it is 0x796500. 0x79 is a code for 'y' and 0x65 is a code for 'e' and the least significant byte is 0x00. Since you are running this on a little endian machine, you get an empty string.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: