gpt4 book ai didi

c - valgrind 中的内存

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:09 25 4
gpt4 key购买 nike

我对 memory inn 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 的声明,但从用法上看它的artisttitle 成员是char * 指针。您可以使用 sizeof 来测量数组,但不能测量指针指向的 block 。 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) ;

关于c - valgrind 中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26228006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com