valgrind中的记忆

时间:2014-10-07 03:12:27

标签: c memory-management valgrind

我遇到了记忆旅馆valgrind的问题。我一直想弄清楚什么是错的,但我似乎无法找到它。这是我的问题:

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

这就是问题所在。

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 ;

}

我尝试过取消引用并为malloc添加更多空间。我知道strcpy出了问题,但我不确定原因。

1 个答案:

答案 0 :(得分:1)

您没有显示song的声明,但从使用情况来看,artisttitle成员的char*指针似乎是sizeof。您可以使用sizeof来测量数组,但不能使用指针指向的块。 char*对于您机器上的所有strlen(str)+1指针都是相同的,无论它们指向的字符串有多长。

您需要使用sizeof(str)+1代替d->artist = malloc(strlen(s->artist) + 1) ; strcpy(d->artist, s->artist) ; d->title = malloc(strlen(s->title) + 1) ; strcpy(d->title, s->title) ; 来解决此问题:

{{1}}