title: Heap corruption during free()
body: <p>Here is the Debug information,</p>
  
  <pre><code>HEAP[opencv_CoTraining2.exe]: Heap block at 0AD15168 modified at 0AD15594 past requested  size of 424
  Windows has triggered a breakpoint in opencv_CoTraining2.exe.
  
  This may be due to a corruption of the heap, which indicates a bug in opencv_CoTraining2.exe or any of the DLLs it has loaded.
  
  This may also be due to the user pressing F12 while opencv_CoTraining2.exe has focus.
  
  The output window may have more diagnostic information.
  </code></pre>
  
  <p>and here is my code:</p>
  
  <pre><code>void GetKCent(Mat&amp; mat)
  {
      double** tmp=(double**)calloc(mat.rows,sizeof(double*));
      double f[128];
      memset(f,0,sizeof(f));
      double max=0;
      for (int i=0;i&lt;mat.rows;i++) 
      {
          tmp[i]=(double*)calloc(mat.cols,sizeof(double));
          for (int j=0;j&lt;mat.cols;j++)
          {
                  tmp[i][j]=mat.at&lt;float&gt;(i,j);
                  if (tmp[i][j]&gt;max) max=tmp[i][j];
          }
      }
      for (int i=0;i&lt;mat.cols;i++) for (int j=0;j&lt;mat.rows;j++) tmp[j][i]/=max;
      k_means(tmp,mat.rows,128,K_CLUSTER,KMEANSDIS,kcent);
      for (int i=0;i&lt;K_CLUSTER;i++) for (int j=0;j&lt;128;j++) kcent[i][j]*=max;
      for (int i=0;i&lt;mat.rows;i++)free(tmp[i]);
      free(tmp);
  }
  </code></pre>
  
  <p>The fault ocurred in this line,</p>
  
  <pre><code>for (int i=0;i&lt;mat.rows;i++)free(tmp[i]);
  </code></pre>
  
  <p>and the function k_means() doesn't change the first parameter. Who can help me?</p>
  
  <p>P.S. 
  Here is the definition of k_means()</p>
  
  <pre><code>int k_means(double **data, int n, int m, int k, double t, double **centroids)
  </code></pre>
  
  <p>and here is the _double** kcent_ </p>
  
  <pre><code>kcent=(double**)calloc(K_CLUSTER,sizeof(double*));
  for (int i=0;i&lt;K_CLUSTER;i++) kcent[i]=(double*)calloc(128,sizeof(double));
  </code></pre>
  
  <p>I think this part is correctly.</p>