Memory leak after a pointer returns value

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);
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;

}
The way I deal with this is passing a vector by reference containing the pointer, so I can always delete it
This is a memory leak:
1
2
3
4
5
6
7
8
9
10
11
Matrix Matrix::Resize(int m)
{
	Matrix *cc = new Matrix(m); // you never delete this before returning...
	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;
}

You create a new Matrix and then return a copy of that Matrix (because you dereference your pointer).

If you want to return a Matrix (rather than a pointer) then there is no need to use a pointer in the first place:
1
2
3
4
5
6
7
8
9
10
11
Matrix Matrix::Resize(int m)
{
	Matrix cc(m); // Don't use a pointer so the memory will be automatically cleaned up by the compiler.
	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;
}
Last edited on
You need to define a copy constructor and an assignment operator too.
Topic archived. No new replies allowed.