Fgets错误seg错误 [英] Fgets errors seg fault

查看:50
本文介绍了Fgets错误seg错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何理由导致较早编译的程序由于fgets而在某个时间段出现故障?我完全没有更改任何与之相关的代码.突然我相信它无法打开文件,但是我在十五分钟前用文件对其进行了测试....我所做的只是添加了搜索功能,所以我不明白问题是什么....

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.....

是我通过PuTTy连接的服务器吗?

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);

这是已编译,执行正确且此后未更改的代码.GDB说fgets出错.

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

推荐答案

好,它用于工作"的原因是您破坏了一个不重要的内存位置.更改代码后,事情发生了改变,现在您正在破坏一些重要的东西.

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.

您正在将未初始化的指针传递给createarray().您想做类似的事情:

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).

这篇关于Fgets错误seg错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆