views:

299

answers:

5

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?

+5  A: 

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.

Éric Malenfant
+2  A: 

Yes, delete the memory.

John Dibling
+2  A: 

SysAllocString, from the documentation, behaves like this:

This function allocates a new string and copies the passed string into it.

So, yes, once you've called SysFreeString() you can now free your original character array, and the data will be safely copied into the newly allocated BSTR.

The proper way to free a string of wchar_t allocated with new is to use delete[].

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

The proper way to free a BSTR is with SysFreeString():

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

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

jeffamaphone
A: 

The docs for SysAllocString() are pretty clear:

This function allocates a new string and copies the passed string into it.

The string data you pass in is copied - SysAllocString() doesn't use it after it's completed - you're free to deallocate or modify that buffer.

Michael Burr
A: 

To convert wchar_t* to OLECHAR* you need to use 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
Kirill V. Lyadvinsky