c - 免费功能给出了错误

标签 c memory-leaks segmentation-fault malloc free

我在函数中使用 malloc。函数结束我调用自由函数来避免内存泄漏。但是,如果我调用免费电话,当我的程序无法正常工作时,我会遇到段错误。谁能知道为什么?我用注释标记了这些地方(如果我在这里放置 free(line),我会遇到段错误。如果我不这样做,就会发生内存泄漏)。这是我的代码:

void checkOccurrences(FILE *inp, char *wanted, int lineCount, int limit)
{
char option;
    char *line = malloc(INT_MAX * sizeof(char));
    int i, dif, lineNumber = 0;                 /*i for count, dif means difference*/
    char *temp, *checkpoint;
    while(fgets(line, INT_MAX, inp) != NULL) /*gets line by line*/
    {
        dif = strlen(line) - strlen(wanted);    /*for limit for loop*/
        ++lineNumber;                           /*increase line number*/
        for(i = 0; i < dif; ++i)                /*difference times loop*/
        {
            temp = strstr(line, wanted);    /*first occurrence address on line*/
            if(temp != NULL)                /*if there is occurrence*/
            {      /*temp>checkpoint condition means if there is new occurrences*/
                if(temp > checkpoint)
                {
                    ++lineCount;
                    if((lineCount % limit) == 0)
                    {
                        printLine(lineNumber);
                        checkpoint = temp;
                        printf("more(m) or quit(q) ");
                        scanf(" %c", &option);              /*get option*/
                        if(option == 'q')
                        {
                            /*If I put free(line) here I get seg fault*/
                            /*If I don't it occurs memory leak*/
                            exit(0);                /*end program*/
                        }
                    }
                    else
                    {
                        printLine(lineNumber);
                        checkpoint = temp;
                    }
                }
            }
            ++line;                         /*next address on line*/
        }
    }
    /*If I put free(line) here I get seg fault*/
    /*If I don't it occurs memory leak*/
}

/*GIT121044025*/

最佳答案

看起来您正在循环内更改 line,因此您没有释放从 malloc()

获得的相同指针

你应该复制一份指针用于在循环中修改,并保留原始指针。

您可能还想考虑做一些比预先分配可能大量的内存更不可怕的事情,以防万一,然后在没有错误检查的情况下使用它。

(您不检查曾经分配过的内存,并且您的 fgets 始终假设您有 INT_MAX 字节可用,即使在您将指针递增到缓冲区之后也是如此)。

关于c - 免费功能给出了错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22451693/

相关文章:

C-SYSMALLOC : Assertion failed (realloc)

读取txt文件时无法分隔列

delphi - 连接关闭后如何释放DataSnap内存?

c++ - 如果我中断调试,Visual Studio 会释放内存吗?

java - 垃圾收集器对象的内存泄漏

c++ - 尝试从其自己的类访问公共(public)变量时出现奇怪的 SIGSEGV

c - 将指针传递给 scanf() 会产生段错误

c - 为什么在连接字符串时会出现段错误?

c - 在编译时查找任何 float 最接近的 2 次方

c - 无论键入的数字如何,变量 INT 类型都接收 0