Search code examples
cmemorymemory-managementmemory-leaksvalgrind

Memory leak C -Valgrind


My main function looks like this and Valgrind throws me a memory leak on the second getline. I have two while cycles. The first end is by typing ENTER and the second by EOF. The omitted functionality should have no effect on the problem. What can be the problem? that I have getline twice?

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

Solution

  • 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. I do not see where word is free'd if the second while happens to loop twice. When you make word NULL again and getline mallocs over this probably freaks out valgrind.