2014-10-07 77 views
1

我遇到了memory inn 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中出錯,但我不知道爲什麼。

+0

可能重複http://stackoverflow.com/questions/8269048/length-of -array合功能參數) – 2014-10-07 03:17:11

回答

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) ; 
[長度數組的函數自變量(的