Debugging Valgrind in C
I am still learning valgrind and c. How do I remove "Invalid Free ()"?
Mistake:
==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)
.......
code:
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;
}
I added free(s);
and s=NULL;
andif(s == NULL)..
structure:
typedef struct song_{
char *artist;
char *title;
mtime *lastPlayed;
}song;
So, I'm not really sure how I would go about solving this problem?
+3
source to share
1 answer
Basically call songDelete( &song1 );
and change songDelete to:
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;
}
This will allow you to actually force the variable into main
, for example song1
, to actually set to NULL after it is freed.
0
source to share