简体   繁体   English

内存泄漏 C -Valgrind

[英]Memory leak C -Valgrind

My main function looks like this and Valgrind throws me a memory leak on the second getline .我的主函数看起来像这样,Valgrind 在第二个getline上抛出了内存泄漏。 I have two while cycles.我有两个while循环。 The first end is by typing ENTER and the second by EOF.第一个结束是通过输入 ENTER 和 EOF 的第二个结束。 The omitted functionality should have no effect on the problem.省略的功能应该对问题没有影响。 What can be the problem?可能是什么问题? that I have getline twice?我有两次getline

    while (1) 
    {   
        phrases = NULL;
        size = 0;

        charactersCnt = getline (&phrases, &size, stdin);

        if ( (int) charactersCnt < 1)
        {
             free(phrases);
             free(fraze);
             return 0;
        }

        ...

        if ( phrases[0] == '\n')
        {
            break;
        }
     } 
     while (1) 
     {
         word = NULL;
         size = 0;

         if ((i = getline (&word, &size, stdin)) == EOF)
             break;

         sscanf (word, "%[^\n]s",word);
         int c = 0;
         ...
    }

    for(int i = 0; i < countSt; i++ ){
        free(lines[i].fraze);
    }

    free(lines);
    free(phrases);
    free(word);

    return 0;
}

The lack on consistent indentation makes this a tough read but I'll take a stab.缺乏一致的缩进使得这很难阅读,但我会尝试一下。

Each time you call getline and word is NULL it allocates an array.每次调用 getline 并且 word 为 NULL 时,它都会分配一个数组。 I do not see where word is free'd if the second while happens to loop twice.如果第二个 while 恰好循环两次,我看不到 word 在哪里被释放。 When you make word NULL again and getline mallocs over this probably freaks out valgrind.当您再次将 word 设为 NULL 并通过 getline mallocs 处理这可能会吓坏 valgrind。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM