我有结构
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的声明,但我不知道是什么
答案 0 :(得分:1)
最简单的方法是使用strdup
复制字符串。
d->artist = strdup(s->artist);
d->title = strdup(s->title);
要解决您的实际问题,您需要使用strlen
而不是sizeof
。
d->artist = malloc(strlen(s->artist) + 1) ;
strcpy(d->artist, s->artist);
d->title = malloc(strlen(s->title) + 1) ;
strcpy(d->title, s->title);
问题在于:
sizeof(*s->artist)
正在返回sizeof(char)
,这很可能是1。