Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am working with a Matrix class to deal with some overloaded operators. I am ha

ID: 3537356 • Letter: I

Question

I am working with a Matrix class to deal with some overloaded operators. I am having a problem of when i run the program I get the error

terminate called after throwing an instance of 'std::bad_alloc'
what(): St9bad_alloc
15112016777216Abort (core dumped)

I believe that to be caused from running off one of the arrays, but i'm not sure and can not find where.


Could really use some help solving this.


I could use help finding out why this code is crashing and what needs to be done to fix it.


The code is as follows.


the input file is

in.txt

3 4

1 2 3 4
0 1 2 3
0 0 1 2

3 4

1 2 5 6
2 1 7 8
0 0 3 2

3 4

3 1 4 1
7 5 8 2
9 4 6 1

4 2

1 2
3 4
5 6
7 8

3 2

4 7
2 5
1 7




Matrix.h file




#ifndef MATRIX_H_
#define MATRIX_H_

#include

using namespace std;

class Matrix
{

public:
    Matrix();
    Matrix(int rows, int columns);
    Matrix(const Matrix& m); //copy constructor
    virtual ~Matrix();

    const Matrix& operator=(const Matrix & rightObject);

    friend Matrix operator+ (const Matrix& a,
                             const Matrix& b);
    friend Matrix operator- (const Matrix& a,
                             const Matrix& b);
    friend Matrix operator* (const Matrix& a,
                             const Matrix& b);
    friend bool operator== (const Matrix& a,
                             const Matrix& b);
    friend bool operator!= (const Matrix& a,
                             const Matrix& b);
    friend std::istream& operator>> (std::istream& is, Matrix& a);
    friend std::ostream& operator<< (std::ostream& os, const Matrix& a);
    int getRows() const;
    int getColumns() const;
    void swap(Matrix& other);

private:

    int         rowSize;
    int         columnSize;
    double**    matrix;

    void initZero();
    void initCopy(const Matrix& m);
};

#endif



Matrix.cpp file





#include
#include
#include
#include

#include "Matrix.h"

using namespace std;

Matrix::Matrix():rowSize(0),columnSize(0),matrix(NULL){}

Matrix::Matrix(int rows, int columns) : rowSize(rows),columnSize(columns){initZero();}
//copy constructor
Matrix::Matrix(const Matrix& m): rowSize(m.rowSize),columnSize(m.columnSize){initCopy(m);}

Matrix::~Matrix()
{
    for (int i = 0; i < rowSize; ++i)
    {
        delete[] matrix[i];
    }
    delete matrix;
}

void Matrix::initZero()
{
    if (rowSize==0&&columnSize==0)
    {
            matrix=NULL;
            return;
    }

    if (rowSize    == 0) throw runtime_error("rows cannot be zero if columns is not zero");
    if (columnSize == 0) throw runtime_error("columns cannot be zero if rows is not zero");

    matrix = new double*[rowSize];
    for (int i = 0; i < rowSize; ++i)
    {
        matrix[i] = new double[columnSize](); //uses default value 0.0
    }
}

void Matrix::initCopy(const Matrix& m)
{
    //ToDo
    for(int i = 0; i < rowSize; ++i)
        {
        for(int j = 0; j < columnSize; ++j)
            {
            matrix[i][j] = m.matrix[i][j];
            }
        }   
}

void Matrix::swap(Matrix& other)
{
    std::swap(rowSize,other.rowSize);
    std::swap(columnSize,other.columnSize);
    std::swap(matrix,other.matrix);
}

//overload the assignment operator
const Matrix& Matrix::operator=(const Matrix & rightObject)
{
    Matrix temp(rightObject);

    swap(temp);
    return *this;
}


Matrix operator+ (const Matrix& a,
                          const Matrix& b)
{
    if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)
        throw runtime_error("Cannot add different size matrices");

    Matrix temp(a.rowSize,a.columnSize);

    for (int i = 0; i < a.rowSize; i++)
    {
        for (int j = 0; j < a.columnSize; j++)
        {
            temp.matrix[i][j] = a.matrix[i][j] + b.matrix[i][j];
        }
    }

    return temp;
}

Matrix operator- (const Matrix& a,
                          const Matrix& b)
{
    //ToDo
    if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)
        throw runtime_error("Cannot add different size matrices");

    Matrix temp(a.rowSize,a.columnSize);

    for (int i = 0; i < a.rowSize; i++)
    {
        for (int j = 0; j < a.columnSize; j++)
        {
            temp.matrix[i][j] = a.matrix[i][j] - b.matrix[i][j];
        }
    }

    return temp;
}

Matrix operator* (const Matrix& a,
                          const Matrix& b)
{
    //ToDo
    Matrix prod(a.rowSize, b.columnSize);
    for(int i = 0; i < prod.rowSize; ++i)
        {
        for(int j = 0; j < prod.columnSize; ++j)
            {
            for(int k = 0; k < a.columnSize; ++k)
                {
                prod.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j];
                }
            }
        }
    return prod;
}
bool operator== (const Matrix& a,
                const Matrix& b)
{
    if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)
        return false;

    for (int i = 0; i < a.rowSize; i++)
    {
        for (int j = 0; j < a.columnSize; j++)
        {
            if(a.matrix[i][j] != b.matrix[i][j]) return false;
        }
    }

    return true;
}
bool operator!= (const Matrix& a,
                const Matrix& b)
{
    return !(a==b);
}
ostream& operator<< (ostream& os, const Matrix& a)
//overload the stream insertion operator <<
{
    //ToDo
   
    int rows, columns;
    os << rows << columns;
    if(!os) return os;
   
    Matrix temp(rows, columns);
   
    for(int i = 0; i < rows; ++i)
    {
    cout << i << endl;
        for(int j = 0; j < columns; ++j)
        {
        cout << j << endl;
            os << temp.matrix[i][j] << " ";
        }
        os << endl;
    }
    return os;
}

istream& operator>> (istream& is, Matrix& a)
    //overload the stream extraction operator >>
{
    int rows, columns;
    is >>rows>>columns;
    if (!is) return is;

    Matrix temp(rows,columns);

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            is >> temp.matrix[i][j];
            if (!is) return is;
        }
    }
   
    temp.swap(a);
    return is;
}

int Matrix::getRows() const
{
    return rowSize;
}

int Matrix::getColumns() const
{
    return columnSize;
}


TestMatrix.cpp file




#include
#include
#include

#include "Matrix.h"

using namespace std;

void info(int rows, int columns) //(FYI; I do not use this function in the program)
{
    cout<<"input and="" output="" for="" matrix="" is="" in="" format:="" rows="" columns="" elements="" endl="" br="" void="" readmatrix="" istream="" m="" const="" string="" name="" cout="" enter="" the="" following="" format="" n="" element="" 0="" 1="" previous="" comment="" input="" from="" iostream="" keyboard="" here="" we="" use="" ifstream="" file="" int="" main="" filename="" cin="" indata="" ofstream="" outdata="" open="" c_str="" out="" txt="" to="" do="" test="" with="" this="" data="" change="" size="" of="" matrices="" other="" as="" many="" you="" need="" your="" program="" those="" sets="" matrix1="" 3="" 4="" matrix2="" matrix3="" matrix4="" 2="" matrix5="" 3x4="" 4x2="" close="" todo:="" subtraction="" -="">    outData.close();
    return 0;
}



Explanation / Answer

// i have merge all the files during debugging , so if you want to check this code then just copy this code to a seprate file with an extention of .cpp and then compile and run.


//i was not having time, because whwn i submit the code ,only 2 minutes were left


// you can also seprate these codes into separate files





#include <iostream>

#include<fstream>

using namespace std;


#ifndef MATRIX_H_

#define MATRIX_H_

class Matrix

{


public:

Matrix();

Matrix(int rows, int columns);

Matrix(const Matrix& m); //copy constructor

virtual ~Matrix();


Matrix& operator=(const Matrix & rightObject);


friend Matrix operator+ (const Matrix& a,

const Matrix& b);

friend Matrix operator- (const Matrix& a,

const Matrix& b);

friend Matrix operator* (const Matrix& a,

const Matrix& b);

friend bool operator== (const Matrix& a,

const Matrix& b);

friend bool operator!= (const Matrix& a,

const Matrix& b);

friend istream& operator>> (istream& is, Matrix& a);

friend ostream& operator<< (ostream& os, const Matrix& a);

int getRows() const;

int getColumns() const;

void setRows(int r);

void setColumns(int c);

  


private:


int rowSize;

int columnSize;

double** matrix;


void initZero();

void initCopy(const Matrix& m);

};

#endif







Matrix::Matrix():rowSize(0),columnSize(0),matrix(NULL){}


Matrix::Matrix(int rows, int columns) : rowSize(rows),columnSize(columns){initZero();}

//copy constructor

Matrix::Matrix(const Matrix& m): rowSize(m.getRows()),columnSize(m.getColumns()){initCopy(m);}



Matrix::~Matrix()

{

for (int i = 0; i < rowSize; ++i)

{

delete[] matrix[i];

}

delete matrix;

}


void Matrix::setRows(int r)

{

rowSize=r;


}


void Matrix::setColumns(int c)

{

columnSize=c;

}


void Matrix::initZero()

{

if (rowSize==0&&columnSize==0)

{

matrix=NULL;

return;

}


if (rowSize == 0) throw runtime_error("rows cannot be zero if columns is not zero");

if (columnSize == 0) throw runtime_error("columns cannot be zero if rows is not zero");


matrix = new double*[rowSize];

for (int i = 0; i < rowSize; ++i)

{

matrix[i] = new double[columnSize](); //uses default value 0.0

}

}


void Matrix::initCopy(const Matrix& m)

{

initZero();


for(int i = 0; i < rowSize; ++i)

{

for(int j = 0; j < columnSize; ++j)

{

matrix[i][j] = m.matrix[i][j];

}

}   

}




//overload the assignment operator

Matrix& Matrix::operator=(const Matrix & rightObject)

{

setRows(rightObject.getRows());

setColumns(rightObject.getColumns());

initCopy(rightObject);



return *this;

}



Matrix operator+ (const Matrix& a,

const Matrix& b)

{

if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)

throw runtime_error("Cannot add different size matrices");


Matrix temp(a.rowSize,a.columnSize);


for (int i = 0; i < a.rowSize; i++)

{

for (int j = 0; j < a.columnSize; j++)

{

temp.matrix[i][j] = a.matrix[i][j] + b.matrix[i][j];

}

}


return temp;

}


Matrix operator- (const Matrix& a,const Matrix& b)

  

{

//ToDo

if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)

throw runtime_error("Cannot add different size matrices");


Matrix temp(a.rowSize,a.columnSize);


for (int i = 0; i < a.rowSize; i++)

{

for (int j = 0; j < a.columnSize; j++)

{

temp.matrix[i][j] = a.matrix[i][j] - b.matrix[i][j];

}

}


return temp;

}


Matrix operator* (const Matrix& a,const Matrix& b)

  

{

if(a.getColumns()!=b.getRows())

{

cout<<" Error: -- no of rows not equall to no of columns ";

return a;

}


Matrix result(a.getRows(),b.getColumns());

double sum=0;

for(int i=0;i<result.getRows();i++)

for(int j=0;j<result.getColumns();j++)

{

sum=0;

for(int k=0;k<result.getColumns();k++)

sum+=a.matrix[i][k]*b.matrix[i][k];


result.matrix[i][j]=sum;


}

return result;

}

bool operator== (const Matrix& a,const Matrix& b)

  

{

if (a.rowSize != b.rowSize || a.columnSize != b.columnSize)

return false;


for (int i = 0; i < a.rowSize; i++)

{

for (int j = 0; j < a.columnSize; j++)

{

if(a.matrix[i][j] != b.matrix[i][j]) return false;

}

}


return true;

}

bool operator!= (const Matrix& a, const Matrix& b)

  

{

return !(a==b);

}

ostream& operator<< (ostream& os, const Matrix& a)

//overload the stream insertion operator <<

{

//ToDo

int rows=a.getRows();

int columns=a.getColumns();

os << rows <<" "<< columns<<endl<<endl;

if(!os) return os;


for(int i = 0; i < rows; ++i)

{

  

for(int j = 0; j < columns; ++j)

{

os << a.matrix[i][j] <<" ";

}

os << endl;

}

return os;

}


//overload the stream extraction operator >>


istream& operator>>(istream& is, Matrix& a)

{

int rows, columns;

is >>rows>>columns;

if (!is) return is;


a.setRows(rows);

a.setColumns(columns);


a.matrix = new double*[rows];

for (int i = 0; i < rows; ++i)

{

a.matrix[i] = new double[columns](); //uses default value 0.0

}



for (int i = 0; i < rows; ++i) {

for (int j = 0; j < columns; ++j) {

is >> a.matrix[i][j];

if (!is) return is;

}

}

return is;

}


int Matrix::getRows() const

{

return rowSize;

}


int Matrix::getColumns() const

{

return columnSize;

}










void info(int rows, int columns) //(FYI; I do not use this function in the program)

{

//cout<<"input and="" output="" for="" matrix="" is="" in="" format:="" rows="" columns="" elements="" endl="" br="" void="" readmatrix="" istream="" m="" const="" string="" name="" cout="" enter="" the="" following="" format="" n="" element="" 0="" 1="" previous="" comment="" input="" from="" iostream="" keyboard="" here="" we="" use="" ifstream="" file="" int="" main="" filename="" cin="" indata="" ofstream="" outdata="" open="" c_str="" out="" txt="" to="" do="" test="" with="" this="" data="" change="" size="" of="" matrices="" other="" as="" many="" you="" need="" your="" program="" those="" sets="" matrix1="" 3="" 4="" matrix2="" matrix3="" matrix4="" 2="" matrix5="" 3x4="" 4x2="" close="" todo:="" subtraction="" -=""> outData.close();

// return 0;

}


int main()

{

char inputFile[30];

char outputFile[30];

Matrix a;

Matrix b;

Matrix result;

cout<<"Enter the name of the input file : ";

cin>>inputFile;

cout<<"Enter the name of the output file: ";

cin>>outputFile;


ifstream in(inputFile);

ofstream out(outputFile);


if(!in)

{

cout<<"input file does not exists ";

}


if(!out)

{

cout<<"output file doesnot exists ";

}


in>>a;

in>>b;

result=a+b;


out<<a;


out<<endl;


out<<b;


out<<endl;


out<<result;


system("pause");


return 0;


}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote