When i try run with the reviews.csv file the code gives segmention fault don't know why!!
Can someone HELP me with that...
In guião1v2.h only are the structs made for this.
In the code i add some comments for being much easier understand what i'm doing.I don't know how to fix this!!
#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;
}
Segmentation faults occurs only incase there are some memory issues. The code above uses command line argument as well as dynamic allocation through malloc. I suggest remove the command line arguments from main() to make the code looks simpler. The problem here related to memory so try to specify memory statically not dynamically using malloc(),calloc() etc.