I'm using xcode and instruments to find my memory leak, it is complaining that this following code creates memory leak:
double **cn2;
cn2= new double*[noOfItem];
for(int i=0;i<noOfItem;i++)
{
cn2[i]=new double[noOfItem];
}
for(int i=0;i<noOfItem;i++)
{
for(int j=0;j<noOfItem;j++)
{
cn2[i][j]=getCN2(noOfItem,i,j,pearson,cn2CutOff);
//cout<<i<<" "<<j<<" "<< cn[i][j]<<endl;
}
}
for(int i=0;i<noOfItem;i++)
{
delete [] cn2[i];
}
delete [] cn2;
This is the function of getCN2, it is used to fill the 2d array:
double getCN2(int _isize,int _i1,int _i2,double **sim,double _cutoff)
{
//cout<< med<<" "<<med1<<endl;
int count=0;
for(int i=0; i<_isize; i++)
{
//if(sim[_i1][i]>_cutoff && sim[_i2][i]>_cutoff)
if(sim[_i1][i]>sim[_i1][_i2] && sim[_i2][i]>sim[_i1][_i2] && sim[_i1][_i2]>0)
{
count++;
}
}
//cout << rez/sqrt(rez1*rez2) <<endl;
return count;
}
And there is no memory leak if I change my code into:
double **cn2= new double*[noOfItem];
for(int i=0;i<noOfItem;i++)
{
cn2[i]=new double[noOfItem];
}
for(int i=0;i<noOfItem;i++)
{
for(int j=0;j<noOfItem;j++)
{
cn2[i][j]=getCN2(noOfItem,i,j,pearson,cn2CutOff);
//cout<<i<<" "<<j<<" "<< cn[i][j]<<endl;
}
}
for(int i=0;i<noOfItem;i++)
{
delete [] cn2[i];
}
delete [] cn2;
The only possible reason I could think of is that when I call double **cn2; it points to something already and when I call cn2= new double*[noOfItem]; it points to something else and the original **cn2 didn’t get freed? Has anyone else encountered this problem before? It is really weird...Do I have to write them in one line instead of 2 when using new to allocate?