从文件读取时出现分段错误

时间:2020-04-29 20:06:51

标签: c pointers struct segmentation-fault allocation

我正在处理结构和char指针(字符串)。我想制作一个结构数组,这些结构有一个char*和两个int

尝试fscanfarraystruct时出现分段错误。

这是我代码的相关部分。

结构默认

typedef struct {
    char* title;
    int gross;
    int year;
} Movie;

我遇到的功能

Movie* createArray(char *filename, int size)
{

    FILE *f;
    f = fopen(filename, "r");
    Movie* arr = (Movie*) malloc(sizeof(Movie) * size);
    if(!arr){printf("\nAllocation Failed\n"); exit(1);}
    for (int i =0; i<size; i++){
        fscanf(f, "%s %d %d", (arr+ i)->title, &arr[i].gross, &arr[i].year);
    }
    fclose(f);
    return arr;

}

在需要的情况下添加它,这就是我调用函数的方式

        Movie* arr = createArray(file1, records);

1 个答案:

答案 0 :(得分:2)

title是未初始化的指针,您还需要为其保留内存,或者如果需要的话,只需将title声明为具有所需大小的char array

我想在您的函数中解决其他一些问题,您可能会意识到,其中一些带有注释的代码。

Movie* createArray(char *filename, int size)
{
    FILE *f;

    if(!(f = fopen(filename, "r"))){ //also check for file opening
        perror("File not found");
        exit(EXIT_FAILURE); //or return NULL and handle it on the caller
     }  

    //don't cast malloc, #include <stdlib.h>, using the dereferenced pointer in sizeof
    //is a trick commonly  used to avoid future problems if the type needs to be changed
    Movie* arr = malloc(sizeof(*arr) * size);    

    if(!arr) {
        perror("Allocation Failed"); //perror is used to output the error signature
        exit(EXIT_FAILURE);
    }

    for (int i =0; i<size; i++) {
        if(!((arr + i)->title = malloc(100))){ // 99 chars plus null terminator, 
            perror("Allocation failed");       // needs to be freed before the array
            exit(EXIT_FAILURE);   //using EXIT_FAILURE macro is more portable 
        }

        //always check fscanf return, and use %99s specifier 
        //for 100 chars container to avoid overflow
        if(fscanf(f, "%99s %d %d", (arr+ i)->title, &arr[i].gross, &arr[i].year) != 3){ 
            exit(EXIT_FAILURE); //or return NULL and handle it on the caller
        }
    }
    fclose(f);
    return arr;
}