我还在学习 valgrind 和 c。如何消除“无效的 free()”?
错误:
==31415== Invalid free() / delete / delete[] / realloc()
==31415== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31415== by 0x400EE1: songDelete (song.c:44)
==31415== by 0x400B70: main (songtest.c:117)
==31415== Address 0x51fd9f0 is 0 bytes inside a block of size 14 free'd
==31415== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31415== by 0x400EE1: songDelete (song.c:44)
==31415== by 0x400AD3: main (songtest.c:105)
.......
代码:
void songDelete(song *s)
{
if(s == NULL){
return;
}
//artist
free(s->artist) ;
//title
free(s->title) ;
//time
if(NULL != s->lastPlayed)
mtimeDelete(s->lastPlayed) ;
//song
free(s) ;
s = NULL;
}
我添加了 free(s);
和 s=NULL;
和 if(s == NULL)..
结构:
typedef struct song_{
char *artist;
char *title;
mtime *lastPlayed;
}song;
所以我不太确定如何解决这个问题?
最佳答案
在 main 中,调用 songDelete( &song1 );
并将 songDelete 更改为:
void songDelete(song **s)
{
if(*s == NULL){
return;
}
//artist
free((*s)->artist) ;
//title
free((*s)->title) ;
//time
if(NULL != (*s)->lastPlayed)
mtimeDelete((*s)->lastPlayed) ;
//song
free(*s) ;
*s = NULL;
}
这将允许您实际导致 main
中的变量,例如 song1
在释放后实际设置为 NULL。
关于c - 在 C 中调试 Valgrind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26209114/