简体   繁体   English

memcpy创建分段错误

[英]memcpy creates segmentation fault

I have the following code, which takes an unsorted list of songs and artists and sorts and displays them. 我有以下代码,其中包含未排序的歌曲和艺术家列表,并对它们进行排序和显示。

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

I took the code for memcpy almost directly off of the example here , so I am confused as to why this doesn't work. 我几乎直接从此处的示例中删除了memcpy的代码,因此对于为什么此方法不起作用感到困惑。 Can someone help me fix this? 有人可以帮我解决这个问题吗?

edit: 编辑:

this is the initialization of SongList 这是SongList的初始化

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

This line: 这行:

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

should be: 应该:

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

since both songs and totalList.unsortedSongs will decay to pointers which is analogus to the first example in the reference you cited: 因为songstotalList.unsortedSongs都将衰减为指针,这totalList.unsortedSongs您引用的参考中的第一个示例:

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

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

Memcpy expects the source and destination variables to be pointers ( void * ) Memcpy希望源变量和目标变量是指针(void *)

totalList.unsortedSongs is a pointer. totalList.unsortedSongs是一个指针。

When you write &totalList.unsortedSongs you are asking for the address of the pointer. 当您编写&totalList.unsortedSongs时,您正在询问指针的地址。 A bit like "the pointer to the pointer"... See here: http://www.cplusplus.com/doc/tutorial/pointers/ 有点像“指向指针的指针” ...参见此处: http : //www.cplusplus.com/doc/tutorial/pointers/

I just compiled your code and it works fine. 我只是编译了您的代码,所以效果很好。

However, I find your initializer list rather curious. 但是,我发现您的初始化器列表很奇怪。 While it works, it makes me think you actually want to define an array of an array of char[80], not just an array of char[80]. 虽然有效,但让我认为您实际上想定义char [80]数组的数组,而不仅仅是char [80]的数组。

So I think your display routine might be wrong and your debugger just not showing you the real line where things go wrong, because of optimization or whatnot. 因此,我认为您的显示例程可能是错误的,并且由于优化或其他原因,调试器只是没有向您显示出哪里出错了。

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

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