简体   繁体   中英

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. Can someone help me fix this?

edit:

this is the initialization of 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:

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

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

Memcpy expects the source and destination variables to be pointers ( void * )

totalList.unsortedSongs is a pointer.

When you write &totalList.unsortedSongs you are asking for the address of the pointer. A bit like "the pointer to the pointer"... See here: 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].

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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