Is FreeHGlobal() required to free unmanaged string passed in a function?

224 views Asked by At

If I have the following piece of code :

void foo (String^ v)
{
   WCHAR someString[256];
   _tcscpy_s(someString, (LPCTSTR)Marshal::StringtoHGLobalUni(v).ToPointer());
}

Would I still need to use FreeHGlobal() in this case? And if so, why? Would the copy function not take care of this global allocation?

1

There are 1 answers

4
David Yaw On BEST ANSWER

Yes, FreeHGlobal is necessary. _tcscpy_s has no knowledge of where the buffer came from; it doesn't know to free the buffer.

If you wanted an automatic free, you'll want to use some object that is smart enough to do the free when it leaves scope. marshal_context is a good choice here.

void foo (String^ v)
{
    marshal_context context;
    WCHAR someString[256];
    _tcscpy_s(someString, context.marshal_as<const TCHAR*>( v ));
} // <-- The marshal_context, and the unmanaged memory it owns, 
  //     are cleaned up at the end of the function.

(Disclaimer: I'm not at a compiler, there may be syntax errors.)