Question

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?

Was it helpful?

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.

OTHER TIPS

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 SysAllocString you can free your original character array, as the data has been 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 Semantics.

Yes, delete the memory.

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top