operator problem

char* data and size are public members of class Base.

"delete[] data;" below causes "Debug Assertion Failed". What is the problem here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Base& Base::operator+(const Base& rhs)
{
	if(rhs.data)
	{
		char *temp = new char[size];
		strcpy(temp, data);

		size = size + rhs.size;
		delete [] data;

		data = new char[size];
		strcpy(data, temp);
		strcpy(data+strlen(temp), rhs.data);

		delete[] temp;

	}
	
	return *this;
}
The only thing that comes to mind is that you're deleting 'data' when it's not pointing to a valid buffer.
It is being constructed correctly.

As per below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Base
{
public:
	int size;
	char *data;
	Base();
	Base(const Base& rhs);
	Base& operator=(const Base& rhs);
	Base& operator+(const Base& rhs);
	~Base();
};



Base::Base()
{
	size = 10;
	data = new char[size];
	data = "Hello";
};



Base::Base(const Base& rhs)
{
	if(rhs.data)
	{
		size = rhs.size;
		data = new char[size];
		strcpy(data, rhs.data);
	}
	else
	{
		size = 1;
		data = new char[1];
		*data = '\0';
	}
};

int main()
{

	Base b1;
	Base b2;
	Base b3;
	b3 = b1+b2;
	
	return 0;
}
Line 19 above is very wrong.

strcpy( data, "Hello" );

Eye of an eagle. Thanks!
Topic archived. No new replies allowed.