Search code examples
memory-leaksvalgrindlexstrdup

Valgrind Memory Leak in strdup


I am doing a small Project. I am checking about memory leaks using the tool Valgrind. When I use this tool, I got the bellow information.

> 584 bytes in 74 blocks are definitely lost in loss record 103 of 104
> ==4628==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
> ==4628==    by 0x41CF8D0: strdup (strdup.c:43)
> ==4628==    by 0x8060B95: main (in mycall)
> 
> LEAK SUMMARY:
> ==4628==    definitely lost: 584 bytes in 74 blocks
> ==4628==    indirectly lost: 0 bytes in 0 blocks
> ==4628==      possibly lost: 0 bytes in 0 blocks
> ==4628==    still reachable: 21,414 bytes in 383 blocks
> ==4628==         suppressed: 0 bytes in 0 blocks
> ==4628== 
> ==4628== For counts of detected and suppressed errors, rerun with: -v
> ==4628== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

These are the codings I have used the function strdup. I have used in LEX code.

{string}    {

    yylval.string = strdup(yytext + 1);
    yylval.string[yyleng - 2] = 0;
    return PPSTRING;
    }

{numvar}        { yylval.string = strdup(yytext);return(PPNUMVAR);      }
{sysnumvar}     { yylval.string = (char *) strdup(yytext);return(PPSYSNUMVAR);  }

I don't know in which point the memory has been leaked.


Solution

  • strdup function allocate necessary memory to store the sourcing string implicitly, you need to free the returned string (i.e., yylval.string in your code) manually.