Search code examples
cpointersfieldfopenfread

c - iterating through field from txt file causes segmentation fault


So I'm creating a program called convert.c that takes in data from a csv file and writes the data to a new textfile called data.bin (but with alterations to the original csv file). One field/column of the csv file in particular contains a column of integers, which were written to the data.bin file. In my analyzeInjuries.c file, I'm trying to write a program that reads in the data.bin file and calculates the total number of integers within that specific column (representing the total number of injuries caused by hurricanes).

I calculated the total number of injuries in my convert.c file and printed it in the terminal. It worked, however when I try to do the same in the analyzeInjuries file, it prints a value of 0. I'm not sure why this is happening as the getfield function and calculations worked fine in convert.c.

I believe there is something wrong with the line char *two = getfield(buf, 2); because when I attempt to print all values in field two, it causes a segmentation fault. Any help with this would be extremely appreciated. I'm really confused as to what went wrong in the analyzeInjuries.c file.

analyzeInjuries.c:

    int numDisast= 0;

    while (fgets (buf, lineCount, fd)) {
        char *second = getfield (buf, 2); //printing second field causes seg fault
        int field = POINTER2INT(second);
        numDisast = numDisast + field;


    }
    printf("%d\n", numDisast);
    return 0;
}

The image below is a screenshot of the data.bin file. The red line indicates the field I'm trying to find the sum of.

enter image description here


Solution

  • I assume that by "printing third field causes seg fault" you mean trying to print second variable.

    getfield() returns NULL if it doesn't find the field and because it uses , as a separator and your data.bin doesn't use ,, then it will always return NULL. Then when you try to print it, it will crash.

    Beside that you are not really summing values in the column. Your POINTER2INT macro does not convert a string to an integer. You probably want to use atoi() instead.

    EDIT

    First: you should check for NULL in you loop:

    char *second = getfield (buf, 3);
    if (second) {
        printf("found field: %s\n", second);
        numDisast = numDisast + atoi(second);
    }
    else {
        printf("field not found\n");
    }
    

    Second: your data.bin looks like it might use tabs instead of , as the separator. You could change "," to "\t" in your call to strsep() and see if it helps.