I need help. Now i'm trying to make a class Matrix, but my program freezes every time I run it in Visual Studio 2013. I think there is some trouble with copy constructor. Here is the whole code. `
class Matrix
{
private:
int** matrix;
int X; // Matrix rows
int Y; // Matrix columns
public:
// Default Constructor
Matrix()
{
X = 0;
Y = 0;
matrix = NULL;
}
// Constructor with parameters
Matrix(int _X, int _Y)
{
srand(time(NULL));
X = _X;
Y = _Y;
matrix = new int*[X];
for (int i = 0; i < X; i++)
matrix[i] = new int[Y];
for (int i = 0; i < X; i++)
{
for (int j = 0; j < Y; j++)
{
matrix[i][j] = rand() % 100;
}
}
}
// Copy constructor
Matrix(const Matrix& N)
{
X = N.X;
Y = N.Y;
matrix = new int*[X];
for (int i = 0; i < X; i++)
matrix[i] = new int[Y];
for (int i = 0; i < X; i++)
{
for (int j = 0; j < Y; j++)
{
matrix[i][j] = N.matrix[i][j];
}
}
}
// Destructor
~Matrix()
{
for (int i = 0; i < X; i++)
delete[] matrix[X];
}
//--------------------------------------
void ShowMatrixOnScreen()
{
for (int i = 0; i < X; i++)
{
for (int j = 0; j < Y; j++)
cout << matrix[i][j] << " ";
cout << endl << endl;
}
}
};
void main()
{
Matrix x(4, 2);
x.ShowMatrixOnScreen();
}
`
Function "ShowMatrixOnScreen" prints matrix "x" on a screen, but then console freezes.
Your destructor has the statement
delete[] matrix[X];
matrix[X]
does not exist, so you are freeing memory which is not allocated to you, which is Undefined Behavior. It should be delete [] matrix[i]
instead!
Moreover, as pointed by Vlad From Moscow, it is advisable to delete
all the memory, so you shall also consider adding delete [] matrix
, to delete the 1-D array of pointers which you allocated using matrix = new int*[X];