尝试读取文件时出现分段错误?

时间:2017-11-18 05:16:11

标签: c file io segmentation-fault

我在argv [1]中传递了fileName,我得到了一个段错误,但我不知道为什么。我正在使用链表来保存包含2个字符和一个int的汽车结构的实例。我觉得问题出在我的fscanf声明中,但我不确定。

void readFile(List *north, List *east, List *south, List *west, char *fileName) {
    char *file = fileName;
    FILE *fp = fopen(file, "r");

    if(!fp) {
        printf("File could not be opened...");
        return;
    }

    while(!feof(fp)) {
        Car *temp = NULL; //Initialize a blank car
        fscanf(fp, "%s %s %d", &temp->direc, &temp->turn, &temp->time); //scan the direction path and time
        //into the Car Node

        //Add to North List
        if(temp->direc == 'N') {
            insertBack(north, temp);
        }

        //Add to East List
        if(temp->direc == 'E') {
            insertBack(east, temp);
        }

        //Add to South List
        if(temp->direc == 'S') {
            insertBack(south, temp);
        }

        //Add to West List
        if(temp->direc == 'W') {
            insertBack(west, temp);
        }

        else {
            printf("Something went wrong...");
            return;
        }
    }
    fclose(fp);
}

1 个答案:

答案 0 :(得分:2)

  

Car *temp = NULL; //Initialize a blank car

您没有初始化"空白"车在这里。 temp变量只是NULL。在malloc之前使用fscanf分配空间:

Car *temp = malloc(sizeof(Car));

如果是"空白"你的意思是将分配的空间归零,使用calloc

相关问题