Program works in release mode, not in debug!

Hello, i've got an assigment that requires me to overload some operators and add some objects together.

I will show the code and explain as good as I can.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void SArray::operator+= (const SArray &obj)
{
	Sphere * tmp_arr;
	tmp_arr = new Sphere[obj.antalobjekt+this->antalobjekt]; //antalobjekt = //Gets amount of elements in the arrays. 

	this->set_arraystorlek(obj.antalobjekt+this->antalobjekt);
//arraystorlek = size of the array.

	std::copy(this->m_arr,this->m_arr+this->get_antal(),tmp_arr);
//get_antal = same as antalobjekt. Just a getter.

	std::copy(obj.m_arr,obj.m_arr+obj.get_antal(),tmp_arr+this>get_antal());

	m_arr = tmp_arr;

	this->antalobjekt = this->antalobjekt+obj.antalobjekt;
	//plussa två SArray

}


Adds a object to another one, using this operator as a base for the + operator.
I think i need to delete somewhere in the operators, i don't really know where.


Anyways, more code.

1
2
3
4
5
6
7
8
9
10
SArray& SArray::operator= (SArray &SA) // i = SA; i.=(SA);
{
	if (this == &SA)
		return *this;
	this->set_antal(SA.get_antal());
	this->set_arraystorlek(SA.get_arraystorlek()+100); //Set size to //arraysize + 100
	memcpy(m_arr, SA.m_arr, (antalobjekt-1)*sizeof(Sphere));

	return *this;
}

1
2
3
4
5
6
SArray SArray::operator+ (const SArray &plusobjekt)
{
	SArray result(*this);
	result += plusobjekt;
	return result;
}



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
int _tmain(int argc, _TCHAR* argv[])
{

	Vec3 obj1;
	obj1.set_x(-0.370182);
	obj1.set_y(-0.006185);
	obj1.set_z(-0.091369);
	Sphere Sphere1(obj1, 0.003105);

	Vec3 obj2;
	obj2.set_x(-0.250182);
	obj2.set_y(-0.005485);
	obj2.set_z(-0.091269);
	Sphere Sphere2(obj2, 0.002705);

	SArray SA2(Sphere2);
	SArray SA(Sphere1);
	SArray test;

	SA2.LäsArrayFrånFil("teapot.txt");
	
	SA.LäsArrayFrånFil("bunny.txt");

	test = SA2 + SA;
	for (int i = 0; i < test.get_antal()+1; i++) 
	{
	cout << test.get_array()[i].get_r() << endl;  // <--Error in debug mode

	}
	/*SA.HittaTvåStörstaMinsta();*/
	int var1;
	cin >> var1;
	return 0;
}


m_arr is the inner array for storing elements, do ask if something is not clear enough. The copy constructor works, so i have not included it.
Last edited on
If line 6 of the SArray::operator+= snippet sets the value that get_antal() retrieves on line 9, you have a problem. You should only be copying the number of objects originally in *this. Also, I don't see any memory deallocated here. Presumably some was previously allocated that should be deallocated or there wouldn't be any objects to copy from *this.


In SArray::operator=, the use of memcpy for class objects is wrong. I don't see any allocation or deallocation of memory here. Is that accomplished in set_arraystorlek?
Topic archived. No new replies allowed.