class matrix{
private:
int n, *wsk;
friend istream & operator>>(istream&,matrix&);
friend ostream & operator<<(ostream&,matrix&);
public:
matrix(){
wsk=0;
n=0;
}
matrix(const matrix &mat){
this->n=mat.n;
if (wsk!=0) delete []wsk;
this->wsk=new int [this->n*this->n];
for (int i=0;i<n*n;i++)
wsk[i]=mat.wsk[i];
}
~matrix(){
if (this->wsk!=0) delete[]this->wsk;
}
const matrix & operator=(const matrix &mat){
if(&mat==this) return *this;
if (this->wsk!=0) delete [] this->wsk;
n=mat.n;
this->wsk=new int [n*n];
for (int i=0;i<mat.n*mat.n;i++)
this->wsk[i]=mat.wsk[i];
return *this;
}
};
istream & operator>>(istream &str, matrix& mat){
str >> mat.n;
if (mat.n>0) {
if (mat.wsk != 0) delete[]mat.wsk;
mat.wsk= new int [mat.n*mat.n];
for (int i=0;i<mat.n*mat.n;i++)
str >> mat.wsk[i];
}
return str;
}
ostream & operator<<(ostream &str, matrix& mat){
if (mat.wsk!=0){
for (int i=0;i<mat.n*mat.n;i++){
str << mat.wsk[i] << " ";
if ((i+1)%mat.n==0) str << endl;
}
}
return str;
}
When I'm trying to make two matrices in main, where firsts dimension is lower than second, double free is happening. When both matrices have the same dimension, or dimension of the first matrix is higher than the second, there is no problem. Maybe someone can see the code and tell me what's the problem?
Edit: Main:
int main(){
matrix mac, a, b;
cout << "Put number of dimensions and numbers in matrix ";
cin >> mac;
cout << mac;
cin >> a;
cout << a;
mac.~matrix();
return 0;
}