2014-10-06 48 views
3

我仍在學習valgrind和c。我如何消除「無效的免費()」?調試Valgrind in C

錯誤:

==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; 

所以我不太清楚我會如何解決這個問題?

+0

song.c中的第44行是什麼?這就是問題所在。 – HuaTham 2014-10-06 01:55:37

+0

@HuaTham在第44行是'免費(s->藝術家);'任何建議? – guy201485 2014-10-06 01:58:00

+0

你的歌曲結構是相關的。據推測藝術家是不可能分配的東西? – 2014-10-06 02:00:10

回答

0

在主,叫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釋放之後。

+0

當我編譯代碼時,它給了我很少的錯誤:'錯誤:對於'songDelete' void songDelete(song ** s)''和更少的錯誤'衝突類型'錯誤:請求成員'藝術家' union free(* s-> artist); ' – guy201485 2014-10-06 02:49:35

+0

您還需要更改代碼中較高的songDelete的原型,如下所示:'void songDelete(song **);' – JohnH 2014-10-06 02:55:45

+0

好吧,我這樣做了,得到這個:'song.c:44: 12:錯誤:請求成員「藝術家」不屬於結構或工會 免費(* s->藝術家);'與標題一起並且被lastplayed。 – guy201485 2014-10-06 03:00:30