i .
i .

Reputation: 485

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

Upvotes: 1

Views: 8766

Answers (3)

tim k
tim k

Reputation: 162

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/

Upvotes: 1

FRob
FRob

Reputation: 4041

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.

Upvotes: 0

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158529

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

Upvotes: 4

Related Questions