2014-10-07 9 views
1

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 :

는이 문제를 해결하기 위해 strlen(str)+1 대신 sizeof(str)+1를 사용할 필요가 -array-in-function-argument) –

답변

1

song 선언을 표시하지 않았지만 사용법에 따라 artisttitle 멤버는 char* 포인터입니다. sizeof을 사용하여 배열을 측정 할 수 있지만 포인터가 가리키는 블록은 측정 할 수 없습니다. sizeof은 컴퓨터에있는 모든 char* 포인터에 대해 동일합니다. 포인터의 길이는 아무리 길어도 상관 없습니다.

d->artist = malloc(strlen(s->artist) + 1) ; 
strcpy(d->artist, s->artist) ; 

d->title = malloc(strlen(s->title) + 1) ; 
strcpy(d->title, s->title) ; 
[함수 인수의 배열의 길이 (의
관련 문제