title: What's the correct way to dynamically resize matrices in Matlab's mex?
body: <p>I am trying to dynamically realloc some arrays in mex depending on dynamic size of input data.</p>
  
  <pre><code>   std::vector&lt;mxArray*&gt; arrays;
     size_t row_size = 1;
  
     for(size_t i = 0; i &lt; col_count; ++i) {
       mxArray* output = mxCreateNumericMatrix(row_size, 1, mxDOUBLE_CLASS, mxREAL);
       arrays.push_back(output);
     }
  
     void grow() {
       size_t new_size = row_size * 2;
       for(size_t i = 0; i &lt; col_count; ++i)
         mxSetM(arrays[i], new_size);
       row_size = new_size;
     }
  
     size_t current_row = 0;
     while(...) {
       if(current_row &gt;= row_size)
         grow();
  
       //do some assignment to the arrays
       double* p = mxGetPr(arrays[col]);
       p[current_row] = value;
  
       ++current_row;
     }
  </code></pre>
  
  <p>This works for awhile, but I am obviously corrupting memory somehow, as it bombs randomly with:</p>
  
  <pre><code>MATLAB: double free or corruption (out): 0x00007f9714314f50 ***
  </code></pre>
  
  <p>If I pre-allocate the "matrix" (<code>grow</code> is never called) everything runs without issue.</p>