c - I could not find the problem with my code
问题描述
This is my class assignment and my first time writing in c. I am trying to read files, store them in a buffer then XOR the read bytes finally store the output to another file. Everything seems correct, but I got a segmentation error. I could not figure out what I have missed. I have tried to find if the functions I used caused this but nothing. I have also searched stackoverflow. I would really appreciate a help.
#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 count,它是 argv(参数向量)数组中的元素数。然而,C 中的索引是从零开始的。因此,如果数组的长度为 n 个元素,则最后一个元素的索引为 n - 1,第一个元素为 0。
编辑:@Weather Vane非常有帮助地指出 argv 中的最后一个元素实际上是一个 NULL(零)值。解释为 char * 这可能是您的段错误。使用 gdb 和 printf 帮助您调试并找出程序何时崩溃很好的 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 运算符的实际工作方式
推荐阅读
- python - 如何检查全局变量是否存在,如果不存在则将其定义为全局变量?
- anova - 创建一个循环以对多个变量的单向重复测量方差分析执行事后分析
- python - 如何从 Object-C 代码中获取 PyRun_SimpleString(s) 输出字符串?
- php - 使用复选框不同的行在数据库中插入数据
- pandas - 如何从 pandas 数据框中获取路径名并将其传递到 pd.read_csv 以使用该路径读取该文件?
- git - 无法推送到 git:无法解析 url
- c# - Outlook VSTO:获取/更新 editBox1 值
- android - 在颤动模式下使用 android studio 进行数字签名 android 应用程序
- javascript - 文件位置电子中的图标未更改
- angular - 如何通过角度事件绑定连接组件?