[英]Memory in 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中出問題了,但是我不確定為什么。
你沒有顯示的聲明song
,但是從使用它看起來像它的artist
和title
成員char*
指針。 您可以使用sizeof
測量數組,但不能測量指針指向的塊。 對於計算機上的所有char*
指針, sizeof
都相同,無論它們指向的字符串多長時間。
您需要使用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) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.