Safe memory management when interfacing code via MEX
9 views (last 30 days)
Show older comments
Joel Andersson
on 23 Jun 2015
Commented: James Tursa
on 11 Jul 2023
I am using MEX to interface to C/C++ code, which includes the creation of objects that will outlive the call to the MEX-function. These objects will eventually be deallocated by subsequent calls to the MEX function. That is, there is persistent memory in the MEX-function.
If I understand things right, I can increase a lock counter using mexLock whenever memory is allocated in my wrappers using either C "malloc" or C++ "new" and then decrease the lock counter using mexUnlock whenever I free objects using C "free" or C++ "delete". That will prevent the MEX function to be released while the function is still in use.
Is this safe usage? I have read that one should always use mxMalloc/mxFree instead of malloc/free, but when interfacing code, this is not an option.
1 Comment
James Tursa
on 11 Jul 2023
Yes this is not only safe, but necessary to prevent memory leaks. The other thing you can do is use a mexAtExit( ) function to free all your dynamically allocated memory when the mex function is cleared.
Accepted Answer
Philip Borghesani
on 23 Jun 2015
Edited: Philip Borghesani
on 23 Jun 2015
Locking the mex file is only needed to preserve static data. Any memory allocated using malloc or new will persist until deleted or matlab exits even if your mex file is unloaded and reloaded.
Use of mxMalloc is only* need to prevent leaks in c (or c style) code that throws exceptions via mexErrMsgIdAndTxt ether directly or indirectly.
*The other not recommended need is when the pointer will be passed to mxSetData or related functions.
More Answers (0)
See Also
Categories
Find more on Write C++ Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!