How to properly free memories after running a MEX file

13 ビュー (過去 30 日間)
Moein Mozaffarzadeh
Moein Mozaffarzadeh 2021 年 10 月 6 日
回答済み: Sivani Pentapati 2021 年 11 月 7 日
Hi,
I have written a MEX function in CUDA and C. When I run this MEX function in a loop, Matlab crashes after 200 iterations (more or less). When i look at the report, it says: memory access violation. See the attachement for more details please.
I've gone through my code and made sure that I use "cudaFree" and "delete [ ]" (at the end of the code) for every "cudaMalloc" and "new" commnad I use to allocate memory in the device (GPU) and host (CPU). I also have used "mexAtExit(cleanup);" at the end.
void cleanup()
{
mexPrintf("Memory cleanup completed, return: %d\n", cudaThreadExit());
return;
}
What else do I need to be careful with? Obviously, I'm missing something. Otherwise, Matlab should not crash, right?
Of course I can use "cudaDeviceReset();" at the end of the code to free up all the memories, but it imposes a delay to my code which is not welcome. So, i do not want to use this command.
Please help.
Moein.

回答 (1 件)

Sivani Pentapati
Sivani Pentapati 2021 年 11 月 7 日
The crashes can be related to creation and destruction of pointers. The following mex functions can be used instead of inbuilt C functions:
  1. mxCalloc can be used in place of calloc
  2. mxMalloc can be used in place of malloc
  3. mxRealloc can be used in place of realloc
  4. mxFree can be used in place of free
  5. If a memory was allocated using mxcreate, mxDestroyArray can be used to free memory

カテゴリ

Help Center および File ExchangeGPU Computing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by