Search code examples
c++windowsstringmemory-managementbstr

Can I free memory passed to SysAllocString?


When allocating a new BSTR with SysAllocString via a wchar_t* on the heap, should I then free the original wchar_t* on the heap?

So is this the right way?

wchar_t *hs = new wchar_t[20];
// load some wchar's into hs...
BSTR bs = SysAllocString(hs);
delete[] hs;

Am I supposed to call delete here to free up the memory? Or was that memory just adoped by the BSTR?


Solution

  • As its name implies, SysAllocString allocates its memory, it does not "adopt" its argument's memory. BSTRs are size-prefixed and null-terminated, so "adopting" a c-style string is impossible, as there is no space for the size prefix.