【问题标题】:Having problems with pointers in cc中的指针有问题
【发布时间】:2014-03-24 15:46:54
【问题描述】:

我有结构

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

【问题讨论】:

  • 据我所知,您需要在这里使用strlen 而不是sizeof sizeof(*s->artist) 和这里sizeof(*s->title) + 1
  • 如果你不喜欢这个问题,删除问题本身,请不要删除你问题的内容,这会让这个问题的其他读者很困惑。
  • 此外,删除这样一个非常好的问题(已成功回答)对于整个 Stack Overflow 来说是完全不考虑的。我希望您的编辑在某种程度上是一个错误。

标签: c debugging pointers valgrind


【解决方案1】:

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

【讨论】:

  • 有关该主题的更多信息,请参阅answer
猜你喜欢
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 2011-08-02
相关资源
最近更新 更多