Can I free memory passed to SysAllocString?
Asked Answered
M

5

9

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?

Madeleinemadelena answered 20/4, 2010 at 17:4 Comment(1)
Kind of funny - I completely misread the variables when I posted my answer (which I subsequently deleted). I "saw" delete[] bs; instead of hs. I must need new glasses.Moira
W
13

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.

Whap answered 20/4, 2010 at 17:7 Comment(0)
I
13

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.

Insipid answered 20/4, 2010 at 17:17 Comment(0)
W
4

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.

Woollyheaded answered 20/4, 2010 at 17:17 Comment(0)
T
3

Yes, delete the memory.

Triliteral answered 20/4, 2010 at 17:9 Comment(0)
V
1

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
Valentine answered 20/4, 2010 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.