Search code examples
c++cmatlabmex

Will mxDestroyArray free reallocated matrix or matrix with changed size correctly?


Question 1:

mxArray *data = mxCreateUninitNumericMatrix(1, 10, mxDOUBLE_CLASS, mxREAL);
mxSetN(data, 0);
mxDestroyArray(data);

Will mxDestroyArray free 10 elements or 0 elements?

Question 2:

mxArray *data = mxCreateUninitNumericMatrix(1, 10, mxDOUBLE_CLASS, mxREAL);
double *ptr = mxGetPr(data);
ptr = static_cast<double*>(mxRealloc(ptr, sizeof(double) * 20));
mxSetPr(data, ptr);
mxDestroyArray(data);

Will mxDestroyArray free 10 elements or 20 elements?

Thank you,


Solution

  • Regarding Q1: At least 10 elements will be freed. Say docs for mxSetN:

    You typically use mxSetN to change the shape of an existing mxArray. The mxSetN function does not allocate or deallocate any space for the pr, pi, ir, or jc arrays. So, if your calls to mxSetN and mxSetM increase the number of elements in the mxArray, enlarge the pr, pi, ir, and/or jc arrays.

    Regarding Q2: In the docs for mxDestroyArray it specifically says that

    mxDestroyArray deallocates the memory occupied by the specified mxArray including:

    • Characteristics fields of the mxArray, such as size (m and n) and type.
    • Associated data arrays, such as pr and pi for complex arrays, and ir and jc for sparse arrays.

    So it will free all sizeof(double) * 20 bytes allocated for ptr.