ebwb
ebwb

Reputation: 264

Segmentation fault while scanning data in from a file

all.

After reading up on segmentation faults, I still can't figure out just where this one's coming from. I know that it's coming from this specific function; everything else in my driver program works.

Worth noting is that all of the styles are of the enumerated data type, StyleT.

The function being called:

openList(&list, "List.txt");

The function's definition:

void openList(VehicleListT *list, char *infilename)
{   
    FILE *infile;
    int i = 0;
    char styleString[20];

    newList(list);

    if((infile = fopen(infilename, "r")) == NULL)
    {
        fprintf(stderr, "ERROR: Cannot open source file!\n");
        exit(1);
    }

    fscanf(infile, "%s\n", list->vehicles[i].vin);
    while(!feof(infile))
    {
        fscanf(infile, "%i\n", list->vehicles[i].year);
        fscanf(infile, "%lf\n", list->vehicles[i].price);
        fscanf(infile, "%s\n", list->vehicles[i].make);

        fscanf(infile, "%s\n", styleString);

        if((strcmp(styleString, "TWO_DOOR")) == 0)
        {
            list->vehicles[i].style = TWO_DOOR;
        }
        if((strcmp(styleString, "FOUR_DOOR")) == 0)
        {
            list->vehicles[i].style = FOUR_DOOR;
        }

        if((strcmp(styleString, "CONVERTIBLE")) == 0)
        {
        list->vehicles[i].style = CONVERTIBLE;
        }

        if((strcmp(styleString, "TRUCK")) == 0)
        {
                list->vehicles[i].style = TRUCK;
        }

        if((strcmp(styleString, "SUV")) == 0)
        {
            list->vehicles[i].style = SUV;
        }

        fscanf(infile, "%s\n", list->vehicles[i].color);
        fscanf(infile, "%s\n", list->vehicles[i].vin);

        i++;
        list->count++;
    }

    fclose(infile);
    return;
}

Upvotes: 2

Views: 501

Answers (2)

Barath Ravikumar
Barath Ravikumar

Reputation: 5836

Among other problems , which i can't find out since i don't have the full code , one obvious mistake , which gives you a segmentation fault in your program is

fscanf(infile, "%i\n", list->vehicles[i].year);
fscanf(infile, "%lf\n", list->vehicles[i].price);

The above lines should be,

fscanf(infile, "%i\n",  &list->vehicles[i].year);
fscanf(infile, "%lf\n", &list->vehicles[i].price);

Upvotes: 1

user1732234
user1732234

Reputation:

A few ideas:

  • Looks like you read the VIN twice (right before the while loop then while in it)? Could you be skipping a line?
  • Could a string be overrunning? IE a 30 char VIN number?
  • Or you're running past the array bounds? Too many cars on the lot? :) I suggest adding a safety check for that. Or doing as a linked list.

I'd check how the data is loading in or print it out at the end of each iteration of that while loop. Also recommend the safety check of erroring out if 'i' gets too big.

Upvotes: 0

Related Questions