0

当我尝试使用reviews.csv 文件运行时,代码给出了分段错误,不知道为什么!
有人能帮帮我吗...
在guião1v2.h 中只有为此制作的结构。
在代码中,我添加了一些注释,以便更容易理解我在做什么。

我不知道如何解决这个问题!!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "guião1v2.h"

#define COUNT 1024
#define MAX_LINE 10000000 //random num (the files given are big)


int main(int arg , char*argv[]){
    
    int i = 0;
    char buffer[COUNT];
    char *buffer2 = malloc(COUNT);
    User *user = malloc(sizeof(User)*MAX_LINE);
    Review *reviews = malloc(sizeof(Review)*MAX_LINE);
//i do the allocation of memory.

    FILE *files;
    files = fopen(argv[1],"r"); //opening the file

    if(files == NULL)
    {
     printf("Failed to open file");//in case of fail to open the file
     exit(1);
    }
    
if(strcmp(argv[1], "reviews.csv") == 0)
     { 
      while (fgets(buffer2,COUNT,files))//trying to pass from the file to the struct
      {
        reviews[i].id = strdup(strsep(&buffer2,";"));
        reviews[i].user_id =strdup(strsep(&buffer2,";"));
        reviews[i].business_id =srdup(strsep(buffer2,";"));
        reviews[i].stars = atof(strsep(&buffer2,";"));
        reviews[i].useful = atoi(strsep(&buffer2,";"));
        reviews[i].funny = atoi(strsep(&buffer2,";"));
        reviews[i++].cool = atoi(strsep(&buffer2,";"));
      }
  
    
      for(int j=0; j < i-1; j++)//testing if the data was well copied.
      {
       printf("%s", reviews[j].id); //param
       printf("%s", reviews[j].user_id); //param
       printf("%s", reviews[j].business_id); //param
       printf("%f", reviews[j].stars);  //param
       printf("%d", reviews[j].useful); //param
       printf("%d", reviews[j].funny);
       printf("%d", reviews[j].cool);
       printf("\n");
      }
    }

  fclose(files); // When i don't need the file i close it
  free(user);//I give free to the memory
  free(reviews);// Same thing
  free(buffer2);
  return 0;
}
4

1 回答 1

-1

仅当存在一些内存问题时才会发生分段错误。上面的代码使用命令行参数以及通过 malloc 进行动态分配。我建议从 main() 中删除命令行参数,以使代码看起来更简单。这里的问题与内存有关,因此请尝试使用 malloc()、calloc() 等静态指定内存而不是动态指定内存。

于 2021-03-13T07:43:38.457 回答