2
votes

I'm trying to overload the + operator for a project that I'm doing but this keeps on happening. I think the reason is that the object I created is getting deleted when the operator is getting invoked. Not sure how to fix it though. Here's part of my code:

Matrix Matrix::operator+ (const Matrix& m) const
{
    //something wrong here
    Matrix sum(rows, cols);

    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            sum.element[i][j] = this->element[i][j] + m.element[i][j];
        }
    }

    return sum;
}

Additional Information

Matrix::Matrix(int r, int c)
{
    rows = r;
    cols = c;
    element = new int *[c];
    for (int i = 0; i < c; i++)
    {
        element[i] = new int[r];
    }
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            element[i][j] = 0;
        }
    }
}


Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}


Matrix::~Matrix()
{
    //freeing up the arrays
    for (int i = 0; i < cols; i++)
    {
        delete[] element[i];
        element[i] = NULL;
    }
    delete[] element;
    element = NULL;
}


Matrix& Matrix::operator= (const Matrix& m)
{
    //problem if rows and cols are longer in the new matrix
    //need to create a temp matrix to expand to new one
    for (int i = 0; i < cols; i++)
    {
        for (int j = 0; j < rows; j++)
        {
            this->element[i][j] = m.element[i][j];
        }
    }
    return *this;
}


int* Matrix::operator[] (int n)
{
    return element[n];
}

The specific error I am getting is:

Debug Assertion Failed!

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

In line 52 which I did this:

 Matrix total = mat + m;

Where mat and m are both object matrices

1
How do you expect us to help you without providing code for Matrix constructor? Especially with assertion errors. - lared
Welcome to stackoverflow :). I agree seeing the matrix constructor would help us understand the problem. Including the specific error you get would also be useful. - eigenchris
Thanks for the advise! Added to the post. - David Ma
Are mat and m the same size? - Barry
Do you do any copying in your program? - Barry

1 Answers

1
votes

I'm guessing the problem is caused by this:

Matrix::Matrix(const Matrix& m)
{
    this->element = m.element;
}

That is an invalid copy constructor for two reasons. First, you're not initializing rows or cols. Second, you'll now have two Matrix objects pointing to the same memory - both of which will delete it on destruction:

{
    Matrix m1(3, 5);
    Matrix m2 = m1;
} // BOOM!

You need to do a deep copy here:

Matrix::Matrix(const Matrix& m)
: rows(m.rows), cols(m.cols)
{
    element = new int *[cols];
    for (int i = 0; i < cols; ++i) {
        element[i] = new int[rows];
        for (int j = 0; j < rows; ++j) {
            element[i][j] = m.element[i][j];
        }
    } 
}