Home > Software engineering >  Memory leak in the implementation of the matrix multiplication operation
Memory leak in the implementation of the matrix multiplication operation

Time:05-30

Memory leak in the implementation of the matrix multiplication operation:

template <typename T>
    class Matrix
    {
    private:
        T *data = nullptr;
        size_t rows;
        size_t cols;

Here is the multiplication operation itself:

Matrix<T> operator*(const Matrix<T> &other)
        {
            Matrix<T> result(rows, other.cols);
            if (cols == other.rows)
            {
                for (size_t i = 0; i < rows; i  )
                {
                    for (size_t j = 0; j < other.cols; j  )
                    {
                        for (size_t k = 0; k < cols; k  )
                        {
                            result.data[i * other.cols   j]  = data[i * cols   k] * other.data[k * other.cols   j];
                        }
                    }
                }
            }
            else
            {
                throw std::logic_error("Matrix sizes do not match");
            }
            return result;
        }

How can I change this method so that it works correctly (and does not fall on tests)?

Here is a link to the class https://godbolt.org/z/4PPYx4Y3j. For some reason, everything works well here, but when I start doing a test:

TEST(testMatrixCalculations, testMultiplication)
{
    myMatrix::Matrix<int> mat1(3, 3);
    myMatrix::Matrix<int> mat2(3, 3);

    for (auto &it: mat1)
    {
        it = 3;
    }

    for (auto &it : mat2)
    {
        it = 3;
    }
    mat1.printMatrix();
    mat2.printMatrix();

    myMatrix::Matrix<int> mat3 = mat1 * mat2;
    mat3.printMatrix();
    for (auto it : mat3)
    {
        ASSERT_EQ(it, 27);
    }
}

Outputs this:

    3 3 3 3 3 3 3 3 3 
    3 3 3 3 3 3 3 3 3 
    -1119477653 32718 -1119477653 32718 775685387 21966 775685387 21966 27 
Failure
    Expected equality of these values:
      it
        Which is: -1119477653
      27

CodePudding user response:

Your result.data is not initialized to 0 but you apply a = operation to it. You must either initialize your Matrix::data member to zero in the Matrix main constructor function, or initialize it preliminary in your multiplication loop.

            for (size_t i = 0; i < rows; i  ) {

                for (size_t j = 0; j < other.cols; j  ) {

                    result.data[i * other.cols   j] = 0;

                    for (size_t k = 0; k < cols; k  ) {

                        result.data[i * other.cols   j]  = data[i * cols   k] * other.data[k * other.cols   j];
                    }
                }
            }
  •  Tags:  
  • c
  • Related