为什么我会遇到分段失败?

为什么我会遇到分段失败?

问题描述:

这是我的代码.我正在做一些处理文件的 C 练习

Here is my code. I am doing some C practice for processing a file

我不认为结构定义是问题,但我也发布了它以提供一些上下文.

I don't think the struct definition is the problem but I post it as well to give some context.

 typedef struct carType Car;
struct carType {
   int vehicleID;
   char make[20];
   char model[20];
   int year;
   int mileage;
   double cost;
   Car *next;
};

我认为是导致分段失败的功能.

And the function that i think is causing the segmentation failure.

 void TextLoad(Car *headPointer)
   {
         char fileName[20];
         //prompt user for name of textfile to print to 
        scanf("%s", fileName);
        FILE *fpt;
        //estabish an IO connection
        fpt = fopen(fileName, "r");
        //current car to be printed
        Car *current;
        current = headPointer->next;
        while(fscanf(fpt,"%d %s %s cost:$%f mileage:%d, vehicleID:%d",&current->year,
    current->make, current->model,&current->cost,&current->mileage, &current->vehicleID) != EOF) 
        {
             current = current->next;
        }
        fclose(fpt);
    }  

我测试这个功能的文件有这个内容

The file that I tested this function had this content

 2014 Toyota Celica cost:$90000 mileage:5000, vehicleID:1
 2014 Toyota Rav4 cost:$4500 mileage:4000, vehicleID:2

我所拥有的基本上是一个结构汽车,我想使用文件中的信息来初始化结构汽车的字段.有谁知道这个分段失败是从哪里来的?我检查了其他线程 fclose() 导致分段错误,以及 代码因分段错误而失败 但我确保调用 fclose 来关闭 IO 连接并且我没有初始化另一个文件指针,但效果很好.我认为问题出在 fscanf 上,但我有正确的格式,不是吗?

What I have is basically a struct car and I want to use info from the file to initialize the fields of the struct car. Does anyone know where this segmentation failure is coming from? I checked on other threads fclose() causing segmentation fault, and Code fails with segmentation fault but I made sure to call fclose to close the IO connection and I didn't initialize another file pointer but that worked fine. I think the problem is the fscanf but I have the right format don't I?

在我看来,您没有为汽车结构分配空间.您创建了一个指针,但随后您必须使用 malloc 为其创建内存.我认为您可以使用 sizeof(carType) 作为 malloc 的参数来获取结构的大小.自从我像这样直接使用 c 以来已经有一段时间了,在 C++ 和 C# 中,您可以使用 new 来调用构造函数,而编译器会进行内存管理.

It looks to me like you are not allocating space for the car struct. You create a pointer, but then you must create memory for it using malloc. I think you can get the size of your struct with sizeof(carType) as the argument for malloc. It's been a while since I used straight c like this, in C++ and C# you can just use new to call a constructor and the compiler does the memory management.

所以它看起来像这样:

Car *current = malloc(sizeof(carType));//you might want to try sizeof(car) if that doesn't work