【发布时间】:2021-06-23 13:51:27
【问题描述】:
我正在尝试读入一个文件以缓冲并使用我的 XOR 加密密钥加密每个字节。我已经像下面这样实现了它,但由于某种原因它出现了段错误。
int main(char argc, char *argv[]) {
fileIn = fopen("data.bin", "rb"); // open input file (binary)
if (fileIn==NULL) {
puts("Error opening input file");
exit (1);
}
// obtain file size.
fseek(fileIn , 0 , SEEK_END);
lSize = ftell(fileIn);
rewind(fileIn);
printf("Filesize: %d bytes.\n", lSize);
// allocate memory to contain the whole file.
buffer = (unsigned char*) malloc (lSize);
if (buffer == NULL) {
puts("malloc for input file buffer failed (not enough memory?)");
exit (2);
}
// copy the file into the buffer.
fread (buffer, 1, lSize, fileIn);
char *enckey = "enckey123";
unsigned char *buf = buffer;
int index = 0;
while (buf < buf + lSize - 1) {
*buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
}
}
就像*buf++ ^= enckey[index++ % 9]; 这样的段错误。
用gdb调试,我可以看到lSize是2000,但是index的值是128585。
我做错了什么?
【问题讨论】:
-
如果
lSize是正数,buf < buf + lSize - 1永远不会是假的,出于同样的原因,数学不等式 x x + 当 h 为正时,h 始终为真。你想要buf < buffer + lSize或只是index < lSize。 -
在调用 fopen 之后,您可以简单地调用 fstat 来获取文件大小,而不是使用
fseek+ftell来获取文件大小,然后调用rewind来获取文件大小。跨度> -
您的代码失败,因为您的变量命名很愚蠢。如果您将
buf重命名为current_position或类似名称,您会发现它更容易。
标签: c segmentation-fault