Do I need to explicitly free the memory in managed C++?
.net, c++, c++-cli, memory-management
Solution
For each:
- `new[]` - `delete[]` should be called
- `new` - `delete` should be called
- `malloc()` - `free()` should be called
- `ref new` / `gcnew` - a memory is deallocated automatically
You should avoid taking care of memory management on your own as much as possible by:
- following RAII idiom
- prefering objects with automatic storage duration over dynamically allocated ones
- taking advantage of smart pointers that will ensure that the memory is freed using the appropriate (explicitly specified) means and it will happen so on every return / exit path (even when an exception is thrown)
- etc.
In this case you used `new[]` for allocation, so you should deallocate this memory by calling:
delete[] mBytes;
Problem
I have managed .net C++ dll, a function inside that do the following: ``` unsigned char* mBytes = new unsigned char[hSize]; ``` How to release this mBytes before return?