Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Can I free memory passed to SysAllocString?

Writer Andrew Henderson

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?

1

5 Answers

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.

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.

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.

Yes, delete the memory.

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.