1

I'm having an issue with memory inn valgrind. I've been trying to figure out what's wrong but I can't seem to find it. Here is my issue:

==32233== Invalid write of size 1
==32233==    at 0x4C2E1E0: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==32233==    by 0x4010C7: songCopy (song.c:102)
==32233==    by 0x4009E6: main (songtest.c:82)
==32233==  Address 0x51fda09 is 0 bytes after a block of size 9 alloc'd
==32233==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==32233==    by 0x4010A4: songCopy (song.c:101)
==32233==    by 0x4009E6: main (songtest.c:82)

And this is where the issue is.

song *songCopy(const song *s)
{
//song *d = NULL ;
mtime *tmp = NULL ;

song *d = malloc(sizeof(song));

d->artist = malloc(sizeof(s->artist) + 1) ;
strcpy(d->artist, s->artist) ;

d->title = malloc(sizeof(s->title) + 1) ;
strcpy(d->title, s->title) ;

if (NULL != s->lastPlayed)
{
    // copy the last played
    tmp = mtimeCopy(s->lastPlayed) ;
    d->lastPlayed = tmp ;
}
else
{
    // set lastPlayed to NULL
    d->lastPlayed = NULL ;
}
return d ;

}

I've tried dereferencing and adding more space to malloc. I know it's going wrong in the strcpy but I'm not sure why.

user2835532
  • 113
  • 1
  • 1
  • 10

1 Answers1

1

You did not show the declaration of song, but from the usage it looks like its artist and title members are char* pointers. You can use sizeof to measure an array, but not a block pointed to by the pointer. sizeof is the same for all char* pointers on your machine, no matter how long is the string to which they point.

You need to use strlen(str)+1 instead of sizeof(str)+1 to fix this problem:

d->artist = malloc(strlen(s->artist) + 1) ;
strcpy(d->artist, s->artist) ;

d->title = malloc(strlen(s->title) + 1) ;
strcpy(d->title, s->title) ;
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523