我试图弄清楚我的valgrind调试有什么问题。我慢慢地学习这个valgrind。
调试:
==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==
代码(songToString函数):
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 ;
}
在songToString中,第147行是sstr = malloc( len ) ;
(第52行):
char * sstr = songToString( song1 ) ;
任何帮助都会很棒。谢谢。
答案 0 :(得分:13)
valgrind
显示泄露的内存已分配,但实际的错误必须跟踪内存结束的位置。
显然,在sstr
分配给main
之后,您永远不会free
。
答案 1 :(得分:-2)
@ o11c 你提出了错误的建议。 见链接: http://c-faq.com/ptrs/passptrinit.html
另一个解决方案是让函数返回指针:
int *f()
{
static int dummy = 5;
return &dummy;
}
...
int *ip = f();