我遇到了记忆旅馆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出了问题,但我不确定原因。
答案 0 :(得分:1)
您没有显示song
的声明,但从使用情况来看,artist
和title
成员的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}}