title: Calling mxDestroyArray on mxArray objects returned from Matlab Compiler Runtime
body: <p>We've been interfacing with a library created from the Matlab Compiler. Our problem is related to an array returned from the library.</p>
  
  <p>Once we're finished with the array, we'd like to free the memory, however, doing this causes occasional segmentation faults.</p>
  
  <p>Here is the Matlab library (<code>bugtest.m</code>)::</p>
  
  <pre><code>function x = bugtest(y)
  
  x = y.^2;
  </code></pre>
  
  <p>Here is the command we used to build it (creating <code>libbugtest.so</code>, and <code>libbugtest.h</code>)::</p>
  
  <pre><code>mcc -v -W lib:libbugtest -T link:lib bugtest.m
  </code></pre>
  
  <p>Here is our C test program (<code>bug_destroyarray.c</code>)::</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #include "mclmcrrt.h"
  #include "libbugtest.h"
  
  #define TESTS 15000
  
  int main(int argc, char **argv) 
  {
      const char *opts[] = {"-nojvm", "-singleCompThread"};
      mclInitializeApplication(opts, 2);  
      libbugtestInitialize();
  
      mxArray *output;
      mxArray *input;
      double *data;
      bool result;
      int count;
  
      for (count = 0; count &lt; TESTS; count++) {
  
          input = mxCreateDoubleMatrix(4, 1, mxREAL);
          data = mxGetPr(input); data[0] = 0.5; data[1] = 0.2; data[2] = 0.2; data[3] = 0.1;
  
          output = NULL;
          result = mlfBugtest(1, &amp;output, input);
          if (result) {
              /* HERE IS THE PROBLEMATIC LINE */
              /*mxDestroyArray(output);*/
          }
  
          mxDestroyArray(input);
      }
  
      libbugtestTerminate();
      mclTerminateApplication();
  }
  </code></pre>
  
  <p>Here is how we compile the C program (creating <code>bug_destroyarray</code>)::</p>
  
  <pre><code>mbuild -v bug_destroyarray.c libbugtest.so
  </code></pre>
  
  <p>We believe that <code>mxDestroyArray(output)</code> is problematic.</p>
  
  <p>We run the following to test crashing:</p>
  
  <ul>
  <li>On each of the 32 cluster nodes.</li>
  <li>Run <code>bug_destroyarray</code>.</li>
  <li>Monitor output for segmentation faults.</li>
  </ul>
  
  <p>Roughly 10% of the time there is a crash. If this is independent across nodes 
  then you might suppose it is crashing roughly 0.3% of the time.</p>
  
  <p>When we take out that problematic line we are unable to cause it to crash.</p>
  
  <p>However memory usage gradually increases when this line is not included.</p>
  
  <p>From  the research we've done, it seems we are <em>not</em> supposed to destroy the array returned, if not, how do we stop from leaking memory?</p>
  
  <p>Thanks.</p>