noctonura
noctonura

Reputation: 13121

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?

Upvotes: 10

Views: 8649

Answers (5)

i_am_jorf
i_am_jorf

Reputation: 54600

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.

Upvotes: 13

Éric Malenfant
Éric Malenfant

Reputation: 14148

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.

Upvotes: 14

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99605

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

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340258

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.

Upvotes: 4

John Dibling
John Dibling

Reputation: 101456

Yes, delete the memory.

Upvotes: 3

Related Questions