【发布时间】:2014-03-24 15:46:54
【问题描述】:
我有结构
typedef struct song_
{
char *artist ;
char *title ;
mtime *lastPlayed ;
} song ;
还有一个函数,它接受一个指向歌曲结构的指针并返回一个指向该歌曲副本的指针
song *songCopy(const song *s){
song *d = NULL ;
mtime *tmp = NULL ;
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 ;
}
我正在用 valgrind 调试它,我在上面的星号行上收到了这个错误消息
Invalid write of size 1
==14096== at 0x402C6C3: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==14096== by 0x8048EC9: songCopy (song.c:104)
==14096== by 0x80487C6: main (songtest.c:82)
==14096== Address 0x41fe7a2 is 0 bytes after a block of size 2 alloc'd
==14096== at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==14096== by 0x8048EAA: songCopy (song.c:103)
==14096== by 0x80487C6: main (songtest.c:82)
我觉得我对 d 的声明方式有所改变,但我不知道是什么
【问题讨论】:
-
据我所知,您需要在这里使用
strlen而不是sizeofsizeof(*s->artist)和这里sizeof(*s->title) + 1。 -
如果你不喜欢这个问题,删除问题本身,请不要删除你问题的内容,这会让这个问题的其他读者很困惑。
-
此外,删除这样一个非常好的问题(已成功回答)对于整个 Stack Overflow 来说是完全不考虑的。我希望您的编辑在某种程度上是一个错误。
标签: c debugging pointers valgrind