Take the 2-minute tour ×

Hey there, assuming I have the following code in a mex routine:

mxArray *newPoint = mxDuplicateArray(prhs[0]);
double *newPointData = mxGetPr(newPoint);
newPoint = mxDuplicateArray(prhs[1]);

do I have than to update newPointData also again to point to the new mxArray? And what about the memory where the first occurance of newPoint points to? Do I than also need to destroy that via mxDestroyArray(newPoint); because if I don't do it, I'll loose the address to it after re-assigning newPoint.


Edit: Bump on this please for a better understanding of memory allocation problem!?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

mxDuplicateArray allocates a new array and copies the data. Each new duplicated array will have its data stored in a different memory region.

So, yes, you have to use mxGetPr() to get the address of the data after each call to mxDuplicateArray().

And naturally, allocated arrays must be deallocated. For that, you need to keep the original pointer to each mxArray created (the one returned by mxDuplicateArray).

Finally, you cannot destroy the mxArray after taking the address of the data (using mxGetPr). Otherwise you are accessing memory which has been deallocated and may be allocated again by other code for a different purpose.

share|improve this answer

Be aware that mxDuplicateArray doesn't do the deep-copy in some cases: http://jp.mathworks.com/matlabcentral/newsreader/view_thread/310346

Bug is not fixed, and documentation on the function is still wrong.

share|improve this answer

Your Answer


