Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
noctonura Avatar asked Apr 20 '10 17:04

noctonura


1 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.

like image 66
i_am_jorf Avatar answered Nov 04 '22 06:11

i_am_jorf