I have a program that uses a class to dynamically allocate an array. I have overloaded operators that perform operations on objects from that class.
When I test this program, the overloaded += works, but -= does not work. The program crashes when trying to run the overloaded -= and I get the following runtime error:
malloc: * error for object 0x7fd388500000: pointer being freed was not >allocated * set a breakpoint in malloc_error_break to debug
In the private member variables, I declare the array like this:
double* array_d;
I then dynamically allocate the array in an overloaded constructor:
Students::Students(int classLists)
{
classL = classLists;
array_d = new double[classL];
}
I have the following two overloaded constructors defined as friends of the Students class:
friend Student operator+= (const Student&, const Student&);
friend Student operator-= (const Student&, const Student&);
These are defined like so:
Student operator+= (const Student& stu1, const Student& stu2)
{
if (stu1.getClassL() >= stu2.getClassL())
{
for (int count = 0; count < stu.getClassL(); count++)
stu1.array_d[count] += stu2.array_d[count];
return (stu1);
}
else if (stu1.getClassL() < stu2.getClassL())
{
for (int count = 0; count < stu1.getClassL(); count++)
stu1.array_d[count] += stu2.array_d[count];
return (stu1);
}
}
Student operator-= (const Student& stu1, const Student& stu2)
{
if (stu1.getClassL() >= stu2.getClassL())
{
for (int count = 0; count < stu2.getClassL(); count++)
stu1.array_d[count] -= stu2.array_d[count];
return (stu1);
}
else if (stu1.getClassL() < stu2.getClassL())
{
for (int count = 0; count < stu1.getClassL(); count++)
stu1.array_d[count] -= stu2.array_d[count];
return (stu1);
}
}
Basically what is happening here is I am comparing two objects with arrays that differ in size based on classL. the getClassL()
function is simply: int Student::getClassL() const {return classLists;}
In case you were wondering, I have overloaded the big three in this way:
1. Destructor: Student::~Student() {delete [] array_d;}
2. Copy Constructor:
Student::Student(const Student &student)
{
classLists = student.classLists;
array_d = student.array_d;
}
3. Assignment operator:
Student &Student::operator=(const Student &student)
{
classLists = student.classLists;
array_d = student.array_d;
}
It is weird that += works but -= does not work, since they are practically the same. I suspect my issue is in the allocation of my dynamic memory, but I am not sure and am seeking expert advice.