フィルターのクリア

Will memory leaks happen when the MEX file contains new & delete or STL containers (C++)?

2 ビュー (過去 30 日間)
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)?
  2 件のコメント
José-Luis
José-Luis 2017 年 9 月 5 日
編集済み: José-Luis 2017 年 9 月 5 日
Philip Borghesani
Philip Borghesani 2017 年 9 月 5 日
編集済み: Philip Borghesani 2017 年 9 月 5 日
SIGINT does not apply here. MATLAB will handle SIGINT and will throw a synchronous c++ exception when it is safe to do so. Under no circumstances should a MEX file attempt to install a signal handler doing so will interfere with MATLAB's signal handler and cause never ending grief.

サインインしてコメントする。

採用された回答

Philip Borghesani
Philip Borghesani 2017 年 9 月 5 日
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.
  2 件のコメント
Eli4ph
Eli4ph 2017 年 9 月 5 日
Great! So the extra work to avoid memory leaks is putting them into smart pointers? Also, forgive my bad understanding, what does 'attempt to free one on object destruction' mean? (I am not completely sure.)
José-Luis
José-Luis 2017 年 9 月 5 日
編集済み: José-Luis 2017 年 9 月 5 日
Great. Learned something today.
So whatever cleanup is needed should be explicitly handled in the destructors?
And if memory is left dangling it will live in limbo until you exit Matlab?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File Exchange启动和关闭 についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!