title: matlab have no response after calling a mex function many times
body: <p>I'm hoping someone can help me with a problem I'm having with some mex code I've written.
      After calling the same mex function many times, the matlab will have no response. I post the code here:</p>
  
  <pre><code>void mexFunction(int nlhs, mxArray *plhs[], /* Output variables */
          int nrhs, const mxArray *prhs[]) /* Input variables */
  {
      const char *fieldnames[3]; //This will hold field names.
      fieldnames[0] = (char*)mxMalloc(20);
      fieldnames[0] = "mean";
  
      plhs[0] = mxCreateCellMatrix(11, 1);
      mxArray *cells = plhs[0];
  
      mxArray *treeNodeMean;
      double *mean;
      for(int i = 0; i &lt; 10; ++i) {
          mxArray* treeNode  = mxCreateStructMatrix(1,1,1,fieldnames);
          mxSetCell(cells, i , treeNode);//set treeNode to tree
  
          //initialize
          treeNodeMean  = mxCreateDoubleMatrix(2,58, mxREAL);
  
          //set values
          mean = mxGetPr(treeNodeMean);
  
          for(int j = 0; j&lt;=(58*2);j++) {
              mean[j] = (double)j;
          }
  
          //set treeNode
          mxSetFieldByNumber(treeNode,0,0, treeNodeMean);//(pointer,index,fieldNumber,value)
      }
      return;
  }
  </code></pre>
  
  <hr>
  
  <ol>
  <li>When I call the mex function in the command window as fllow:</li>
  </ol>
  
  <hr>
  
  <blockquote>
    <blockquote>
      <p>for i = 1:100</p>
      
      <p>A = createTrees;</p>
      
      <p>end</p>
    </blockquote>
  </blockquote>
  
  <hr>
  
  <p>Matlab not responding after long runing.</p>
  
  <ol start="2">
  <li>If I delete the code:</li>
  </ol>
  
  <hr>
  
  <pre><code>for(int j = 0; j&lt;=(58*2);j++) {
      mean[j] = (double)j;
  }
  </code></pre>
  
  <hr>
  
  <p>from the mex function, the case of “Matlab not responding after long runing.” will disappear.
  So, How can I solve the "No response" problem.
  Thanks a lot.</p>