Can I free the memory transferred to SysAllocString?

When distributing a new BSTR using SysAllocString via wchar_t * on the heap, do I have to free the original wchar_t * on the heap?

So is this the right way?

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

Should I call delete here to free memory? Or is this memory just adopted by the BSTR?

+7
c ++ string memory-management windows bstr
source share
5 answers

As its name implies, SysAllocString allocates its memory; it does not "accept" its memory of arguments. BSTRs have a size and a prefix with a value of zero, so "accepting" a c-style string is not possible because there is no room for a size prefix.

+9
source share

SysAllocString (), from the documentation , behaves as follows:

This function selects a new line and copies the passed line into it.

So yes, as soon as you call SysAllocString, you can free the original character array as the data was copied to the newly allocated BSTR.

The correct way to free the wchar_t line highlighted with new[] is to use delete[] .

 wchar_t *hs = new wchar_t[20]; ... delete[] hs; 

The correct way to free BSTR with SysFreeString () :

 BSTR bs = SysAllocString(hs); ... SysFreeString(bs); 

While you're new to BSTR, you should read Eric's Complete Guide to BSTR Semantics .

+10
source share

Yes, delete memory.

+3
source share

The docs for SysAllocString() pretty clear:

This function selects a new line and copies the passed line into it.

The string data you pass is copied - SysAllocString() does not use it after it is complete - you can free or change this buffer.

+3
source share

To convert wchar_t* to OLECHAR* , you need to use the W2OLE macro:

 wchar_t *hs = new wchar_t[20]; USES_CONVERSION; BSTR bs = SysAllocString( W2OLE(hs) ); delete[] hs; // no need in hs anymore since SysAllocString allocates memory ... SysFreeString( bs ); // delete Sys string 
0
source share

All Articles