-1

I'm trying to write a method to overload the * operator for multiplying matrices. the matrix it self has its data stored in a dynamically allocated array "_mat_arr" and after running a valgrind check i cant seem to free it properly after finishing with this method.

Matrix Matrix::operator* (const Matrix& rhs)
{
    Matrix new_mat(this->_rows,rhs._cols);
   /*...code to fill the product matrix...*/
    return new_mat;
}

this is my destructor

~Matrix() /*destructor*/
    {
        delete [] _mat_arr;
        _mat_arr = nullptr;
    }

this is my class constructor where i allocate the matrix array

Matrix(int rows, int cols):_rows(rows),_cols(cols)
    {
        _mat_arr = new int [cols*rows];
        for(int i = 0; i < rows * cols; i++)
        {
            _mat_arr[i] = 0;
        }
        _rowLen = _cols -1;
    }

edit: changed delete to delete[]. after running the debugger i think that the problem is that the destructor is not called on new_mat which is allocated inside the method.

Serofin
  • 57
  • 1
  • 5

1 Answers1

0

Your destructor does not use the correct delete. It should call the array version of delete, delete [].

You should also apply Rule of 3 here. Since you are allocating dynamic memory and defining a destructor, you should also define a copy constructor and a copy assignment operator.

Matrix(const Matrix& other);
Matrix& operator=(const Matrix& other);
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • the problem still persists even after changing to delete [ ] in fact nothing changed in the memory check as i still have one memory allocation not freed, also i forgot to mention that i do have a copy constructor and an assignment operator – Serofin Sep 06 '20 at 07:08
  • Sorry, your question got closed by an over-eager person with too much power. Can you request reopening this one so someone else can have a shot at it? – Tanveer Badar Sep 06 '20 at 13:45