【问题标题】:getting a segmentation fault when trying to read a file? [closed]尝试读取文件时出现分段错误? [关闭]
【发布时间】:2018-05-01 22:43:06
【问题描述】:

我正在为文件名传递 argv[1] 并且我遇到了段错误,但我不知道为什么。我正在使用链表来保存包含 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);
}

【问题讨论】:

  • 请使用所有警告和调试信息进行编译:gcc -Wall -Wextra -g 然后使用调试器gdb
  • 我使用的是 Mac,但无法正常工作
  • 你应该可以在终端中使用gdb

标签: c file io segmentation-fault


【解决方案1】:

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

您没有在此处初始化“空白”汽车。 temp 变量就是 NULL。先用malloc分配空间,再用fscanf

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

如果“空白”是指将分配的空间清零,请使用calloc

【讨论】:

  • 我感觉很特别,谢谢
猜你喜欢
  • 2019-12-03
  • 2013-10-20
  • 2018-06-27
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多