c segmentation fault fgets

后端 未结 2 1641
半阙折子戏
半阙折子戏 2021-01-24 11:31
int main( int argc, char** argv) {

        FILE *inFilePtr = fopen(*(argv + 1), \"r\");
        char *rawdata = malloc(sizeof(char) * 100);
        float *ary = malloc(         


        
相关标签:
2条回答
  • 2021-01-24 11:55

    Try casting your malloc calls with (char *)

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

    0 讨论(0)
  • 2021-01-24 12:14

    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 讨论(0)
提交回复
热议问题