class Matrix
{
private:
int m_nrows;
int m_ncols;
double** m_data;
void init()
{
m_data = new double*[m_nrows];
for(int i = 0; i < m_nrows; i++)
m_data[i] = new double[m_ncols];
}
// clean up
void free()
{
if(m_data != NULL)
for(int i = 0; i < m_nrows; i++) delete [] m_data[i];
delete [] m_data;
}
public:
// constructor
Matrix(int nrows, int ncols):m_nrows(nrows), m_ncols(ncols) // Zeros
{
init();
for (int i = 0; i < nrows; i++)
for (int j = 0; j < ncols; j++)
m_data[i][j] = 0.0;
}
Matrix(int nrows, int ncols, const double *val):m_nrows(nrows), m_ncols(ncols) // Initialized by 1D Array
{
init();
for (int i = 0; i < nrows; i++)
for (int j = 0; j < ncols; j++)
m_data[i][j] = *val++;
}
//Operators =, +
Matrix & operator = (const Matrix &rhs)
{
if (this != &rhs){
if(m_nrows != rhs.m_nrows || m_ncols != rhs.m_ncols){
m_nrows = rhs.m_nrows;
m_ncols = rhs.m_ncols;
}
free();
init();
for (int i = 0; i < m_nrows; i++)
for (int j = 0; j < m_ncols; j++)
m_data[i][j] = rhs.m_data[i][j];
}
return *this;
}
Matrix operator + (const Matrix &rhs)
{
if (m_nrows == rhs.m_nrows && m_ncols == rhs.m_ncols ){
Matrix new_mat(m_nrows, m_ncols);
for (int i = 0; i < new_mat.m_nrows; i++)
for (int j = 0; j < new_mat.m_ncols; j++)
new_mat.m_data[i][j] = m_data[i][j] + rhs.m_data[i][j];
return new_mat;
}
else
std::cerr << "Operator '+' Matrix dimensions must agree";
}
};
int main()
{
double x[6] = { 1, 2, 3, 4, 5, 6};
Matrix a
Matrix b(2,3,x);
Matrix c(2,3,x);
a = c;
a.print();
std::cout<<std::endl;
c = a+b;
return 0;
}
Hello,
This code is for doing simple 2d matrix operations. However, I just cannot get the operator "+" right. The rest of code is valid under my testing. There is something wrong, but I just cannot find it. NEED YOUR HELP!
The error message shows * glibc detected * ./a.out: double free or corruption (out): 0x0000000001ec4160 ***. or Segmentation fault: 11 using different compilers.