从文件中读取数据时出现分段故障

问题描述 投票:0回答:1

我正在处理结构体和char指针(字符串)。我想做一个结构体的数组,这些结构体有一个 char*和两个 ints.

当我试图在进行以下操作时,出现了一个分段故障 fscanf 进入 arraystructs.

下面是我代码的相关部分。

结构定义

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);
c pointers struct segmentation-fault allocation
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.