【问题标题】:memcpy creates segmentation faultmemcpy 创建分段错误
【发布时间】:2013-06-18 00:04:21
【问题描述】:

我有以下代码,它采用未排序的歌曲和艺术家列表,并对它们进行排序和显示。

int main()
{
   SongList totalList; // has a public 2d array 'unsortedSongs' variable
   char songs[100][80] =
   {
      {"David Bowie 'Ziggy Stardust'",},
      {"Smokey Robinson 'You've Really Got A Hold On Me'",},
      {"Carole King 'You've Got A Friend'",},
      // many more songs here totaling to 100
      {"Joni Mitchel 'A Case Of You'",},
      {"Prince 'Kiss'"}

   };
   memcpy(&totalList.unsortedSongs, &songs, sizeof(songs)); // this causes a segmentation fault
   totalList.displaySortedList();
   return 0;
}

我几乎直接从示例 here 中获取了 memcpy 的代码,所以我很困惑为什么这不起作用。有人可以帮我解决这个问题吗?

编辑:

这是 SongList 的初始化

class SongList
{
public:
   char unsortedSongs[100][80];
public:
   void displaySortedList();
   void sortList();
   string rearrange(char[]);
   string getSongsForArtist(int*);
};

【问题讨论】:

  • 你能告诉我们SongList是如何声明和实现的吗?我猜unsortedSongs 没有正确初始化。
  • 您确定需要&songs 而不仅仅是songs? (unsortedSongs 可能也一样,但我们不知道...
  • 我真的不认为memcpy:http://ideone.com/lJKboC的行中存在分段错误。
  • 虽然在回到这个问题后我所说的在技术上是不正确的,但我看不出它是如何解决根本问题的。您的大小不匹配,在复制和粘贴时已更正,或者问题确实出在 displaySortedList 中。似乎我无法删除我的答案,因为它已被接受,所以您可以添加 displaySortedList 的代码。

标签: c++ multidimensional-array segmentation-fault 2d memcpy


【解决方案1】:

这一行:

memcpy(&totalList.unsortedSongs, &songs, sizeof(songs));

应该是:

memcpy(totalList.unsortedSongs, songs, sizeof(songs));

因为songstotalList.unsortedSongs 都将decay 指向指针,这类似于您引用的参考文献中的第一个示例:

memcpy ( person.name, myname, strlen(myname)+1 );

【讨论】:

  • @0x499602D2 道歉,我分心了,但我更新了答案。
  • 我不明白为什么通过一元 & 运算符将数组传递给 memcpy 会导致分段错误。 Here is 一个完整的解释为什么这应该起作用。
【解决方案2】:

http://www.cplusplus.com/reference/cstring/memcpy/

Memcpy 期望源变量和目标变量是指针 (void *)

totalList.unsortedSongs 是一个指针。

当您编写 &totalList.unsortedSongs 时,您正在询问指针的地址。有点像“指向指针的指针”...... 看这里: http://www.cplusplus.com/doc/tutorial/pointers/

【讨论】:

    【解决方案3】:

    我刚刚编译了你的代码,它工作正常。

    但是,我发现您的初始化列表相当好奇。虽然它有效,但它让我觉得您实际上想要定义一个 char[80] 数组的数组,而不仅仅是一个 char[80] 数组。

    所以我认为你的显示例程可能是错误的,而你的调试器只是因为优化或诸如此类的原因而没有向你显示真正出错的地方。

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多