Search code examples
c++multidimensional-arraysegmentation-fault2dmemcpy

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

Solution

  • 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 );