Question about matlab mex-file memory
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
.
Thanks!
Edit: Bump on this please for a better understanding of memory allocation problem!?
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.
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.
精彩评论