C语言 Valgrind 块肯定会丢失在丢失记录中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26289262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Valgrind blocks are definitely lost in loss record
提问by user4127382
I am trying to figure out what is wrong with my valgrind debugging. I am learning this valgrind slowly.
我想弄清楚我的 valgrind 调试出了什么问题。我正在慢慢学习这个 valgrind。
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):
代码(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 ;
}
In songToString, line 147 is sstr = malloc( len ) ;
在songToString中,第147行是 sstr = malloc( len ) ;
in songTest (line 52):
在songTest(第52行)中:
char * sstr = songToString( song1 ) ;
Any help would be great. Thank you.
任何帮助都会很棒。谢谢你。
回答by o11c
valgrindis showing you where the leaked memory was allocated, but the actual bug has to be tracked to where that memory ends up.
valgrind正在向您显示泄漏内存的分配位置,但必须跟踪实际错误到该内存的最终位置。
Obviously after you assign to sstrin main, you never freethat.
显然,在您分配给sstrin 之后main,您再也不会free那样了。
回答by stacker
@o11c You gave wrong advice. See link: http://c-faq.com/ptrs/passptrinit.html
@o11c 你给出了错误的建议。见链接:http: //c-faq.com/ptrs/passptrinit.html
Another solution is to have the function return the pointer:
另一种解决方案是让函数返回指针:
int *f()
{
static int dummy = 5;
return &dummy;
}
...
int *ip = f();

