I have the following block of code:
IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
SomeCommandThatCanThrowAnException();
Marshal.FreeHGlobal(unmanagedPointer);
Should the block be wrapped in a try, and the FreeHGlobal command be placed in a finally block. (In case the middle command throws an exception).
It seems to make sense that finally would prevent memory leaks in this case, however from examples that I have found online, finally is not used. Perhaps the resources get automatically disposed of anyway (even though they are unmanaged).
Unmanaged memory allocated with Marshal.AllocHGlobal is not automatically released.
So putting Marshal.FreeHGlobal in a
finally
block is indeed a good idea:The examples you've found probably omit error handling for brevity.
If you're allocating unmanaged memory for long-term purposes (i.e. not freeing it within the same method), you might be interested in wrapping the pointer in an object that derives from SafeHandle (such as SafeBuffer).
SafeHandle implements the IDisposable pattern, so the unmanaged memory will be freed when you dispose the object or when the garbage collector collects the object. SafeHandle also derives from the CriticalFinalizerObject class which means it will get special treatment from the CLR to make sure the memory is really freed.
Example:
Note: SafeBuffer is quite a beast, so caution is advised.
Note 2: SafeHandles work well with P/Invoke and eliminate the need to pass around IntPtrs entirely.
SafeBuffers are for safely manipulating unmanaged memory from C#, so depending on what you're doing (allocating unmanaged memory for use with P/Invoke, or manipulating unmanaged memory from C#) you should choose SafeHandle or SafeBuffer as base class appropriately.