gpt4 book ai didi

c - c中的指针有问题

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

我有结构

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 的声明方式,但我不知道是什么

最佳答案

最简单的方法是使用 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。

关于c - c中的指针有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21963060/

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