C 中的 XOR 相同数据导致非零值。为什么?

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

如何异或指针指向的两个数据段?

我已经试过了,一个基于 Whosebug 上的类似解决方案,但输出不是我所期望的。

代码如下:

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

    printf("%d\n", *(int*)(c));
}

但输出是:7955712。输出不应该是0吗?我在 "hey" 上对 "hey" 进行异或运算,它在 int 中的值是 0 对吗?

看看这个循环:

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

您正在修改 c 并使用 strlen 计算其长度。在第一个迭代器 strlen returns 0 之后循环停止。

如果将 7955712 转换为十六进制,则为 0x796500。 0x79 是 'y' 的代码,0x65'e' 的代码,最低有效字节是 0x00。因为你是 运行 this on a little endian machine,你得到一个空字符串。

严格来说,由于在将 char 数组读取为 int.

时存在别名违规,因此您的代码行为未定义

你可以把问题的症结改写成定义明确的

#include <stdio.h>
#include <stdint.h>
int main(){    

    int32_t n;
    char* c = &n;
    c[0] = 'h';
    c[1] = 'e';
    c[2] = 'y';
    c[3] = 0;

    for( int j = 0; j < strlen(c); j++){
        c[j] ^= c[j];
    }
    printf("%" PRId32 "\n", n);
}

输出不为零,因为 for 循环只运行一次迭代,因为 strlen 的后续估值将为 0,因为 c[0] 将评估为 NUL 终止符.