Copy constructor - "invalid memory allocation"

So I have a defined copy constructor which deep copies elements of an array, however when I run the program, it crashes and I get the error:

"Invalid allocation size: 4294967295 bytes"

size() method returns a private int variable 'm_size' - which is set to 4000. And I've checked the constructor and m_size is defined before 'data'. So it's not crashing because of that. But from my understanding of the error m_size is not read properly and it crashes!! :/

1
2
3
4
5
6
7
8
9
10
11
CArray::CArray(const CArray &A)
{
	m_size = size(); 

	data = new string[m_size];

	for(int i = 0; i < m_size; i++) // loops through copying elements.
	{
		data[i] = A.data[i];
	}
}



Any ideas why I'm getting the error and why it's not reading m_size properly?!

Thanks for any help guys :)
1
2
3
4
5
6
7
8
9
10
11
CArray::CArray(const CArray &A) : m_size( A.size() ) // *** added
{
	// or: m_size = A.size();  // *** corrected

	data = new string[m_size];

	for(int i = 0; i < m_size; i++) // loops through copying elements.
	{
		data[i] = A.data[i];
	}
}
Last edited on
Consider using std::vector<std::string>> instead of std::string *data

If data were defined as std::vector<std::string>> you could write simply

CArray::CArray(const CArray &A) : data( A.data ) {}

or even

CArray::CArray(const CArray &A) = default;
Last edited on
Thanks for your replies,

@JLBorgess
this way seems interesting, i've not been taught this way.

@vlad from moscow
I need to use an array for this project :)
Topic archived. No new replies allowed.