troubleshooting Question

Managing unmanaged memory assigned to IntPtr by Marshal::AllocHGlobal when an exception is thrown

Avatar of Xtreem
XtreemFlag for United Kingdom of Great Britain and Northern Ireland asked on
Fonts TypographyVisual C++.NET
5 Comments1 Solution1759 ViewsLast Modified:
I have the following code:

using namespace System::Runtime::InteropServices;
void CRCWAssembly::CallCOMMethod(long __gc* status)
{
    try
    {
        IntPtr ip = Marshal::AllocHGlobal(sizeof(*status));
        Marshal::WriteInt32(ipStatus, *status);
        (*comLib)->COMMethod(static_cast<long*>(ipStatus.ToPointer()));

        if (Marshal::ReadInt32(ipStatus) != 0)
        {
            throw new Exception();
        }
        Marshal::FreeHGlobal(ip);
    }
    catch(SEHException *sehEx)
    {
        throw new Exception("COMMethod", sehEx);
    }
}

Of course, if an exception is thrown, the memory allocated to ip (IntPtr) never gets freed up. Short of wrapping it up in a class or putting Marshal::FreeHGlobal all over the place and moving the declaration of ip to outside of the 'try' block, is there any other better method to manage this unmanaged memory in the case of an exception being thrown?
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros