kohai
kohai

Reputation: 133

I keep getting a segmentation fault and I don't know why

I'm writing a linked list program in C and I'm stuck trying to write the linked list to a file. After the program asks the user what name they want to save the file under I enter the name and hit ENTER and then I get a segmentation fault and the program quits. I am lost trying to figure out why. The only thing I can think of is the do..while loop, but I use code like that elsewhere in my program and it works fine. Thanks in advance!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Inventory {
    int partID;
    int quantity;
    float price;
    struct Inventory *next;
};

void saveFile(struct Inventory**);

int main()
{
    struct Inventory *first = address location of first structure in list;

    saveFile(&first);

    return 0;
}

void saveFile (struct Inventory **firstPtr)
{
    struct Inventory *prev = NULL;
    char ext[5] = ".csv";
    char fileName[15];
    char c;

    FILE *fp;

    printf("   What would you like to save your linked list as, up to 14 characters: ");
    scanf("%s", fileName);
    strcat(fileName, ext);

    if((fp = fopen(fileName, "r")) != NULL) {
        printf("   File already exists. Would you like to overwrite? [Y/N] ");
        scanf("\n%c", &c);

        if(c == 'Y' || c == 'y') {
           fclose(fp);
           fp = fopen(fileName, "w+");
        } else {
           printf("   Would you like to add to the list? [Y/N] ");
           if(c == 'y' || c == 'Y') {
               fclose(fp);
               fp = fopen(fileName, "a");
           } else {
               fclose(fp);
               return;
           }
        }

    } else {
        fclose(fp);
        fp = fopen(fileName, "w+");
    }   

    do {
        prev = *firstPtr;
        fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
        prev = prev->next; 
    } while (prev->next != NULL); 

    fclose(fp);
}

Upvotes: 4

Views: 127

Answers (1)

fluter
fluter

Reputation: 13816

Your loop does not guard against the first entry being possibly NULL, try using following to loop through a linked list:

while (prev) {
    fprintf(fp, "%d,%d,%f\n", prev->partID, prev->quantity, prev->price);
    prev = prev->next;
}

Upvotes: 3

Related Questions