title: strange C++Memory leak from 2D array
body: <p>I'm using xcode and instruments to find my memory leak, it is complaining that this following code creates memory leak:</p>
  
  <pre><code>double **cn2;
  cn2= new double*[noOfItem];
  for(int i=0;i&lt;noOfItem;i++)
  {
      cn2[i]=new double[noOfItem];
  }
  for(int i=0;i&lt;noOfItem;i++)
  {
      for(int j=0;j&lt;noOfItem;j++)
      {
          cn2[i][j]=getCN2(noOfItem,i,j,pearson,cn2CutOff);
          //cout&lt;&lt;i&lt;&lt;" "&lt;&lt;j&lt;&lt;" "&lt;&lt; cn[i][j]&lt;&lt;endl;
      }
  
  }
  for(int i=0;i&lt;noOfItem;i++)
  {
      delete [] cn2[i];
  }
  delete [] cn2;
  </code></pre>
  
  <p>This is the function of getCN2, it is used to fill the 2d array:</p>
  
  <pre><code>double getCN2(int _isize,int _i1,int _i2,double **sim,double _cutoff)
  {
      //cout&lt;&lt; med&lt;&lt;" "&lt;&lt;med1&lt;&lt;endl;
      int count=0;
  
      for(int i=0; i&lt;_isize; i++)
      {
          //if(sim[_i1][i]&gt;_cutoff &amp;&amp; sim[_i2][i]&gt;_cutoff)
          if(sim[_i1][i]&gt;sim[_i1][_i2] &amp;&amp; sim[_i2][i]&gt;sim[_i1][_i2] &amp;&amp; sim[_i1][_i2]&gt;0)
          {
              count++;
          }
      }
      //cout &lt;&lt; rez/sqrt(rez1*rez2) &lt;&lt;endl;
      return count;
  }
  </code></pre>
  
  <p>And there is no memory leak if I change my code into:</p>
  
  <pre><code>double **cn2= new double*[noOfItem];
  for(int i=0;i&lt;noOfItem;i++)
  {
      cn2[i]=new double[noOfItem];
  }
  for(int i=0;i&lt;noOfItem;i++)
  {
      for(int j=0;j&lt;noOfItem;j++)
      {
          cn2[i][j]=getCN2(noOfItem,i,j,pearson,cn2CutOff);
          //cout&lt;&lt;i&lt;&lt;" "&lt;&lt;j&lt;&lt;" "&lt;&lt; cn[i][j]&lt;&lt;endl;
      }
  
  }
  for(int i=0;i&lt;noOfItem;i++)
  {
      delete [] cn2[i];
  }
  delete [] cn2;
  </code></pre>
  
  <p>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?</p>