繁体   English   中英

memcpy创建分段错误

[英]memcpy creates segmentation fault

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

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;
}

我几乎直接从此处的示例中删除了memcpy的代码,因此对于为什么此方法不起作用感到困惑。 有人可以帮我解决这个问题吗?

编辑:

这是SongList的初始化

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

这行:

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

应该:

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

因为songstotalList.unsortedSongs都将衰减为指针,这totalList.unsortedSongs您引用的参考中的第一个示例:

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

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

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

totalList.unsortedSongs是一个指针。

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

我只是编译了您的代码,所以效果很好。

但是,我发现您的初始化器列表很奇怪。 虽然有效,但让我认为您实际上想定义char [80]数组的数组,而不仅仅是char [80]的数组。

因此,我认为您的显示例程可能是错误的,并且由于优化或其他原因,调试器只是没有向您显示出哪里出错了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM