I am trying to figure out what is wrong with my valgrind debugging. I am learning this valgrind slowly.
debug:
==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 is sstr = malloc( len ) ;
in songTest (line 52):
char * sstr = songToString( song1 ) ;
Any help would be great. Thank you.
valgrind
is showing you where the leaked memory was allocated, but the actual bug has to be tracked to where that memory ends up.
Obviously after you assign to sstr
in main
, you never free
that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With