1
votes
int main( int argc, char** argv) {

        FILE *inFilePtr = fopen(*(argv + 1), "r");
        char *rawdata = malloc(sizeof(char) * 100);
        float *ary = malloc(sizeof(float) * 50);
        int counter = 0;
        float averageAns;
        int count = 0;


        while (count < 1 ){
            //fgets(rawdata, 50, inFilePtr); //I have tried both
            fscanf(inFilePtr, "%s", rawdata);
            *(ary + counter) = atof(strtok(rawdata, ","));
             counter++;
            *(ary + counter ) = atof(strtok(rawdata, NULL));
            counter++;
            *(ary + counter) = atof(strtok(rawdata, NULL));
             counter++;
            count++;
        }

I cannot for the life of me figure out why I keep getting a seg fault. It will seg fault even without the loop (the count < 1 was just to see if I could make it through once).

It will not work with fgets(), fscanf(). It seg faults when I change the stream in fgets to (stdin), and I mention this because I assumed the file * was the issue, but now I do not think it is. I have made the delimiter in my data file " " and ",".

If anyone know's what I did wrong, I would appreciate it.

2
You can use valgrind, gdb, or several other debugging tools to aid you... have you tried any of them?vanza
also, why not just ary[counter++] = atof(strtok(rawdata, NULL));?Aniket Inge
yes, and I'm not an expert using gdb. It gave me an error code that didn't help.SystemFun
Did you check that inFilePtr isn't NULL?Eric
it isn't null, i have a printf statement that prints the value of argv[1] and it is printing the file name I expect, also that is irrelvant because it won't work with stdin either.SystemFun

2 Answers

2
votes

Your call to fscanf is guaranteed to fail, as you have not provided an output argument. It should look like:

fscanf(inFilePtr, "%s", rawdata);

Your calls to strtok are also invalid. To continue tokenising the same string, the first argument of strtok should be NULL; strtok expects the second argument to still be a valid string.

Each of these issues would cause a segfault on their own. To ease your debugging in future, I would suggest either using a debugger and setting a breakpoint after the statement you are debugging, or commenting out other lines which you might expect to segfault (which typically includes anything that does anything with strings, if your code is in a fragile state.

Also, as a matter of style,

*(ary + counter)

Is normally written

ary[counter]
0
votes

Try casting your malloc calls with (char *)

maybe, just maybe: ary[counter++] = atof(strtok(rawdata, ","));