Should Marshal.FreeHGlobal be placed in a finally block to ensure resources are disposed?
Asked Answered
G

2

8

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).

Grader answered 19/8, 2010 at 20:29 Comment(0)
S
15

Unmanaged memory allocated with Marshal.AllocHGlobal is not automatically released.

So putting Marshal.FreeHGlobal in a finally block is indeed a good idea:

IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
try
{
    Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
    SomeCommandThatCanThrowAnException();
}
finally
{
    Marshal.FreeHGlobal(unmanagedPointer);
}

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.

class HGlobal : SafeBuffer
{
    public HGlobal(int cb)
        : base(true)
    {
        this.SetHandle(Marshal.AllocHGlobal(cb));
        this.Initialize((ulong)cb);
    }

    protected override bool ReleaseHandle()
    {
        Marshal.FreeHGlobal(this.handle);
        return true;
    }
}

Example:

using (var h = new HGlobal(buffer.Length))
{
    h.WriteArray(0, buffer, 0, buffer.Length);
}

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.

Sassenach answered 19/8, 2010 at 20:38 Comment(0)
H
2

Absolutely. It never gets released automatically, it is unmanaged memory.

Hartmann answered 19/8, 2010 at 20:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.