Reviews.csv 中的段错误

问题描述

当我尝试使用 review.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;
}

解决方法

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