I'm trying to do some operations in two dimensional matrices. I overloaded (+ , - and *) to do the calculations. I have a problem regarding (I believe) memory management. Look at the following code:
Mtx M1(rows1,cols1,1.0); //call the constructor
Mtx M2(rows2,cols2,2.0); //call the constructor
Mtx M3(rows3,cols3,0.0); //call the constructor
M3 = M1 + M2;
cout << M3 << endl;
Mtx Mtx::operator+(const Mtx &rhs)
{
double **ETS;
ETS = new double*[nrows];
for (int i = 0; i < rhs.nrows; i++) {
ETS[i] = new double[rhs.ncols];
}
if (ETS == NULL) {
cout << "Error Allocation on the Heap" << endl;
exit(1);
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = 0.0;
}
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = ets[i][j];
}
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ETS[i][j] = ETS[i][j] + rhs.ets[i][j];
}
}
Mtx S(nrows, ncols, ETS);
delete [] ETS;
return S;
}
I think my problem is here:
Mtx S(nrows, ncols, ETS);
delete [] ETS;
return S;
Is this a proper way to return ETS
? Or do you think the problem is with the constructor? I got no output when I did the above return!
This is the constructor for Mtx S(nrows, ncols, ETS);
Mtx::Mtx(int rows, int cols, double **ETS)
{
ets = new double*[nrows];
for (int i = 0; i < nrows; i++) {
ets[i] = new double[ncols];
}
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
ets[i][j] = ETS[i][j];
}
}
}
My copy constructor:
Mtx::Mtx(const Mtx& rhs)
:nrows(rhs.nrows), ncols(rhs.ncols)
{
ets = new double*[nrows];
for (int i = 0; i < nrows; i++) {
ets[i] = new double[ncols];
}
for (int i = 0; i < rhs.nrows; i++) {
for (int j = 0; j < rhs.ncols; j++) {
ets[i][j] = rhs.ets[i][j];
}
}
}
I overloaded <<
to print M3
. It works fine because I tested printing M1
and M2
.
I also did the following, and still not working:
Mtx S(nrows, ncols, ETS);
for (int i = 0; i < rhs.nrows; i++) {
delete [] ETS[i];
}
delete [] ETS;
return S;
}