Valgrind blocks are definitely lost in the loss record.

I am trying to figure out what is wrong with my valgrind debugging. I am slowly assimilating this valgrind.

debugging:

==1701== HEAP SUMMARY:
==1701==     in use at exit: 390 bytes in 12 blocks
==1701==   total heap usage: 59 allocs, 47 frees, 1,097 bytes allocated
==1701==
==1701== 39 bytes in 1 blocks are definitely lost in loss record 6 of 12
==1701==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1701==    by 0x401246: songToString (song.c:147)
==1701==    by 0x40083C: main (songtest.c:52)
==1701==

Code (SongToString Function):

char *songToString(const song *s)
{
    char *sstr = NULL ;
    char *st = NULL ;
    char *sa = NULL ;
    char *tt = NULL ;
    int len = 0 ;

    st = songGetTitle(s) ;
    sa = songGetArtist(s) ;

    // calculate the total string length needed.
    len = strlen("Title: ") + strlen(st) +
                  strlen("  Artist: ") + strlen(sa) + 1 ;

    if (NULL != s->lastPlayed)
    {
        tt = mtimeToString(s->lastPlayed) ;
        len += strlen(" at ") + strlen(tt) ;
    }

    // allocate enough space for the song
    sstr = malloc( len ) ;

    sprintf(sstr, "Title: %s  Artist: %s", st, sa) ;

    if (NULL != s->lastPlayed)
    {
        sstr = strcat(sstr, " at ") ;
        sstr = strcat(sstr, tt) ;
    }

    free(sa) ;
    free(st) ;
    free(tt) ;
    return sstr ;
}

In songToString line 147 sstr = malloc( len ) ;

in songTest (line 52):

char * sstr = songToString( song1 ) ;

Any help would be great. Thank.

+4
source share
2 answers

valgrind shows you where the memory leak was allocated, but the actual error should be tracked where that memory ends.

Obviously, after you are assigned sstrto main, you never have freethis.

+10
source

@ o11c You gave the wrong advice. See Link: http://c-faq.com/ptrs/passptrinit.html

- :

int *f()
{
    static int dummy = 5;
    return &dummy;
}

...

int *ip = f();
-1

All Articles