Will memory leaks happen when the MEX file contains new & delete or STL containers (C++)?
1 view (last 30 days)
Memory Management in documentation says that mxCalloc and mxFree, instead of calloc and free in standard C library, should be used to manage memory.
However, it is sometimes unavoidable to use new & delete when using C++ classes in MEX file, as well as the automatic memory management of STL containers when using them.
Here comes the question. If the user sometimes interrupts the MEX file execution using Ctrl+C, and if the MEX file contains new & delete or STL containers, will memory leaks happen? If so, how to avoid memory leaks (with least extra work)?
Philip Borghesani on 5 Sep 2017
The short answer is: Put anything allocated with a standard allocator into a smart pointer (unique_ptr, shared_ptr,...) and never put a MATLAB allocated object (mxMalloc, mxCreate...) into a smart pointer or attempt to free one on object destruction and you will be fine.
Most of the documentation/API is written from the perspective of C and FORTRAN mex programming and has not been updated for C++ yet. If you are using a supported C++ compiler (I am not completely sure about minGW on Windows) then the normal C++ exception mechanism is used and destructors are run when ctrl-c is used in a mex file.