brian4342
brian4342

Reputation: 1253

Create a deep copy of an array C++

I am try to solve some problems in my program and it would appear that there is either a problem with my copy constructor or with my destructor. I am getting a memory exception.

any help would me appreciated Thanks

ArrayStorage::ArrayStorage(const ArrayStorage &a):readArray(a.readArray),arraysize(a.arraysize)
{
    readArray = new string[arraysize]; //create the array

    memcpy (readArray,a.readArray,sizeof(string)*arraysize);//Copy the values of bytes from the location pointed at by the souce and destination.
}

ArrayStorage::~ArrayStorage(void)
{
    delete[](readArray);//deconstuctor to delete the array.
}

would this be a better way to copy the array other than memcpy :

for (int i = 0 ; i < arraysize ; i ++)
    {
        readArray[i] = a.readArray[i];
    }

Upvotes: 0

Views: 13711

Answers (4)

Lundin
Lundin

Reputation: 214395

That code doesn't make any sense. First you initialize your members to the values passed by the object to copy, through the initializer list. Then you allocate memory for the very same members and copy everything again.

Most likely you are copying junk data into an uninitialized pointer. Get rid of the initializer list :readArray(a.readArray),arraysize(a.arraysize).

Upvotes: 0

Mat
Mat

Reputation: 206841

You can't just memcpy random objects, you need to actually copy them with their copy operators.

string most likely holds a pointer to heap-allocated storage. If you copy it bitwise, calling the destructor on the original string invalidates the "copied" string's data.

Use something like std::copy to do this properly.

#include <algorithm>
...
std::copy(a.readArray, a.readArray+arraysize, readArray);

Upvotes: 10

Nico
Nico

Reputation: 3826

The strings also have dynamic memory, so you'd have to go through each string and make a copy of it.

A fix would be copying each string inside of your array instead of memcopy. The exception is from two different strings having the same pointer to a piece of memory and both trying to free it.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70989

I would not advice you to copy strings the way you do. As the string holds reference to heap memory you in fact copy the pointers and so the strings in both arrays are sharing memory. This is not very c++-ish and quite dangerous. I would advice you to use the assignment operator or copy constructors for the strings(yes do a cycle).

Upvotes: 6

Related Questions