首页 > 解决方案 > 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;
}

标签: cpointersstruct

解决方案


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 运算符的实际工作方式

阅读和一个简单的示例请记住,具有编译时已知大小的数组与可能指向一个或多个元素的指针不同。


推荐阅读