gpt4 book ai didi

c - 变量 int key 多次用作 XOR 运算中的一个输入后发生莫名其妙的变化

转载 作者:行者123 更新时间:2023-11-30 14:52:09 25 4
gpt4 key购买 nike

我正在尝试使用输入的 key 加密 file_1.txt 并将结果输出到 file_2.txt。教授指定文件必须一次读取 100 个字节。

int main(int argc, char *argv[]){
int key;
key = atoi(argv[1]);

FILE *file_pointer;
file_pointer = fopen(argv[2], "rb");

char buffer[100];
char output[sizeof(int)][100];
int output_counter = 0;
int read_counter;
int read_elements;
int buffer_reset_counter;
for(buffer_reset_counter = 0; buffer_reset_counter < 100; buffer_reset_counter++){
buffer[buffer_reset_counter] = 0;
}
while(read_elements = fread(buffer, 1, 100, file_pointer) > 0){
read_counter = 0;
while(read_counter < 100){
printf("xor'ing %d and %d\n", key, buffer[read_counter]);
output[output_counter][read_counter] = buffer[read_counter] ^ key;
read_counter = read_counter + 1;
}
output_counter = output_counter + 1;
for(buffer_reset_counter = 0; buffer_reset_counter < 100; buffer_reset_counter++){
buffer[buffer_reset_counter] = 0;
}
}

fclose(file_pointer);

file_pointer = fopen(argv[3], "wb");
int write_counter = 0;
while(write_counter < output_counter){
fwrite(output[write_counter], 1, 100, file_pointer);
write_counter = write_counter + 1;
}
}

file_1.txt 是字符串“用于测试的测试文件\n”重复 100 次。

前几百次打印的输出与预期一致,但随后 key 发生了变化:

xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 105
xor'ing 111 and 110
xor'ing 111 and 103
xor'ing 111 and 10
xor'ing 111 and 116
xor'ing 111 and 101
xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 32
xor'ing 111 and 102
xor'ing 111 and 105
xor'ing 111 and 108
xor'ing 111 and 101
xor'ing 111 and 32
xor'ing 111 and 102
xor'ing 111 and 111
xor'ing 111 and 114
xor'ing 111 and 32
xor'ing 111 and 116
xor'ing 111 and 101
xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 105
xor'ing 6 and 110
xor'ing 26630 and 103
xor'ing 6383622 and 10
xor'ing 207710214 and 116
xor'ing 207710214 and 101
xor'ing 207710214 and 115
xor'ing 207710214 and 116
xor'ing 207710214 and 32
xor'ing 207710214 and 102
xor'ing 207710214 and 105
xor'ing 207710214 and 108
xor'ing 207710214 and 101
Segmentation fault (core dumped)

我不知道 key 是如何变化的。如果相关,printf("%d", sizeof(int)); 输出 4。

早些时候,我提交了一个关于垃圾进入缓冲区数组的问题(stackoverflow.com/q/47732691/905902),因为它在使用 fread() 之前没有初始化。这次的问题是 key 意外改变。

最佳答案

在声明中:

output[output_counter][read_counter] = buffer[read_counter] ^ key;

output_counter 可以大于 sizeof(int) 如果循环运行超过四次,即有超过 400 个字节(我认为)文件。发生这种情况时,异或操作会覆盖堆栈,从而写入key的存储。

更高级别,您确实想学习使用诸如 valgrind 或 clang 的地址清理器之类的工具,因为它们会很快发现此类问题。

关于c - 变量 int key 多次用作 XOR 运算中的一个输入后发生莫名其妙的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com