这是我的类作业,也是我第一次用 c 语言写作。我正在尝试读取文件,将它们存储在缓冲区中,然后对读取的字节进行异或运算,最终将输出存储到另一个文件中。一切似乎都是正确的,但我遇到了段错误。我不知道我错过了什么。 我试图找出我使用的功能是否导致了这个但没有。我也搜索了计算器。非常感谢您的帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int BUFFER_SIZE = 10000;
const long FILE_SIZE = 100000000;
typedef struct file_buffer_struct
{
char * buffer;
FILE * pFile;
} file_buffer;
int main (int argc, char *argv[] ) {
printf("hello | ");
FILE *outputF ;
int i;
int j;
int k;
int result;
file_buffer FB[10];
outputF = fopen ( argv[argc] , "wb");
if ( (argc < 4) && (argc > 13) ) // argc should be greater than 4 or less than or equal to 12 for correct execution
{
printf( "please give arguments greater than 3 and less than 11 !");
return 0;
}
//xor_all_buffers(&FB, &outputF);
for(i=1; i<argc; i++)
{
FB[i].pFile = fopen( argv[i] , "rb" );
FB[i].buffer = (char*) malloc (sizeof(char)*BUFFER_SIZE);
}
char * xored_buffer = (char *) malloc(BUFFER_SIZE);
for (int index=0; index < FILE_SIZE ;) {
memset(xored_buffer, 0, sizeof(xored_buffer));
for (int i=0; i < sizeof(FB); i++) {
for (int j=0; j < BUFFER_SIZE; j++, index++) {
xored_buffer[j] = xored_buffer[j] ^ FB[i].buffer[index];
}
}
result=fwrite(xored_buffer, sizeof(char), BUFFER_SIZE, outputF);
}
printf("hello | ");
return 0;
}
最佳答案
outputF = fopen ( argv[argc] , "wb");
Argc 代表 arg 计数,它是 argv(参数 vector )数组中的元素数。但是 C 中的索引是从零开始的。因此,如果数组的长度为 n 个元素,则最后一个元素的索引为 n - 1,第一个元素为 0。
编辑:@Weather Vane 所以很有帮助地指出 argv 中的最后一个元素实际上是一个 NULL(零)值。解释为 char * ,这可能是您的段错误。使用 gdb 和 printf 帮助您调试并找出程序何时崩溃 nice intro to gdb
if 条件
if ( (argc < 4) && (argc > 13) )
一般来说,在尝试使用 argc 之前应该进行检查。想想如果没有论据会怎样?为什么要用后检查。你也可能想重新考虑这种情况。什么时候小于 4 和大于 13。也许您打算使用 OR?
for(i=1; i<argc; i++)
同样的问题索引也是从零开始的。
xored_buffer[j] ^ FB[i].buffer[index]
你到底在哪里设置了FB[i].buffer[index]的值
您可能还想检查 sizeof 运算符的实际工作方式
reading和一个 simple example请记住,编译时大小已知的数组不同于可能指向一个或多个元素的指针。
关于c - 我找不到我的代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521192/