Hello everyone,
Can anyone help me with memory leak. I found memory leak with the pointer Matrix *cc = new Matrix(m) in the function below when I used valgrind check the memory usage. 16 bytes in 1 blocks are definitely lost.
Matrix Matrix::Resize(int m){
Matrix *cc = new Matrix(m);//memory leak here
for (int i=0;i<m;i++){
for (int j=0;j<m;j++){
cc->val[i][j]=val[i][j];
cout<< cc->val[i][j] << endl;
}
}
return *cc;
cerr << "post return\n";
/*delete [] cc->val;
delete & cc;
delete [] cc;*/
}
In the main program (shown below), another pointer was defined and the allocated memory was released by using delete.It seems that 'delete [] cc' doesn't work in the function after return value. Is there any way to release memory assigned within this function? Or is there any other way to make this program work? Thanks in advance.
Here is the whole program:
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix(){val = NULL;num=0;};
Matrix(int);
Matrix(int, double);
~Matrix(){
for (int i=0;i<num;i++){
delete [] val[i];
}
delete [] val;
};
Matrix Resize(int m);
private:
double **val;
int num;
};
Matrix::Matrix(int n){
num=n;
val = new double * [n];
for (int i=0;i<n;i++){
val[i] = new double [n];
for (int j=0;j<n;j++){
val[i][j]=0;
cout<< val[i][j] << endl;
}
}
};
Matrix::Matrix(int n, double dd){
num=n;
val = new double * [n];
for (int i=0;i<n;i++){
val[i] = new double [n];
for (int j=0;j<n;j++){
val[i][j]=dd;
cout<< val[i][j] << endl;
}
}
};
Matrix Matrix::Resize(int m){
Matrix *cc = new Matrix(m); // cause memory leak: 16 bytes in 1 blocks are definitely lost in loss
for (int i=0;i<m;i++){
for (int j=0;j<m;j++){
cc->val[i][j]=val[i][j];
cout<< cc->val[i][j] << endl;
}
}
return *cc;
cerr << "post return\n";
/*delete [] cc->val;
delete & cc;
delete [] cc;*/
}
main()
{
Matrix *cc1 = new Matrix(4, 5.5); // No memory leak because it can be released using 'delete'.
Matrix c=cc1->Resize(1);
delete cc1;
}
