Fgets errors seg fault

你离开我真会死。 提交于 2019-12-02 14:23:28

问题


Is there any reason that a program, which compiled earlier, should seg fault at a point because of fgets? I changed no code related to it AT ALL. Suddenly I believe it is failing to open the file, but I tested it with the file like fifteen minutes ago.... All I did was add a search function, so I don't understand what the issue is.....

Could it be the server I'm connecting to over PuTTy?

int createarray( int **arrayRef, FILE *fptr){
    int size = 0, i;
    char rawdata[100];

    while (fgets(rawdata, 99, fptr) != NULL){
        size++;
    }

    rewind(fptr);
    *arrayRef = malloc(sizeof(int) * size);

    for ( i = 0; i < size; i++ ){
     fgets(rawdata, 99, fptr);
     *(*arrayRef + i) = atoi(rawdata);
    }


    return size;
}


      int main ( int argc, char **argv ) {  //main call

    // declare variable to hold file
    FILE *inFilePtr = fopen(*(argv + 1), "r");
    int **aryHold;
    int numElements, sortchoice, key, foundindex;

    // Call function to create array and return num elements
    numElements = createarray(aryHold, inFilePtr);

This is the code that compiled, performed correct, and hasn't been changed since. GDB says there is an error with fgets.


回答1:


OK, the reason it use to "work" is you were clobbering an unimportant memory location. Changing your code shifted things around and now you are clobbering something important.

You're passing an uninitialized pointer to createarray(). You wanted to do something like:

int* aryHold;
//...
... createarray(&aryHold ... 

BTW, many compilers have the ability to catch this kind of error for you. If you haven't already, you might want to see if your compiler has an error checking option that could have saved you hassling with this (and perhaps find some other code that only "works" accidentally).



来源:https://stackoverflow.com/questions/14825162/fgets-errors-seg-fault

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!