Tech Support > Microsoft Windows > Development Resources > Does ::SysAllocString() make a copy of the wchar_t buffer?
Does ::SysAllocString() make a copy of the wchar_t buffer?
Posted by Boogie El Aceitoso on January 14th, 2004


Hi,

I have a function that returns a BSTR. This function created a BSTR by passing
a wchar_t array to ::SysAllocString().

Is is safe to then delete[] the array? Does ::SysAllocString() make a copy?

TIA

Posted by Stephen Kellett on January 14th, 2004


In message <14ca0014up9t6p0i0baodl521nr69epfku@4ax.com>, Boogie El
Aceitoso <frr149@telefonica.net> writes
No, don't delete [] the array. That will use the wrong allocator.

Use
SysAllocFreeString(array);

Stephen
--
Stephen Kellett
Object Media Limited http://www.objmedia.demon.co.uk
RSI Information: http://www.objmedia.demon.co.uk/rsi.html

Posted by Boogie El Aceitoso on January 14th, 2004


On Wed, 14 Jan 2004 13:22:41 +0000, Stephen Kellett
<snail@objmedia.demon.co.uk> wrote:

It's not the BSTR I want to free, it's a raw wchar_t pointer, used to create
the BSTR.

Here's the code:
--------------------------------------------------------------------
using namespace std;

BSTR string2BSTR( const string & input )
{

int destSize = input.size() + 1;
wchar_t * rc;
wchar_t * wc = new wchar_t[destSize];
BSTR res;

rc = ::StringToWideChar(input.c_str(), wc, destSize);

if( rc == wc )
{
// funcionó
res = ::SysAllocString(wc);
}
else
{
// cascó
res = ::SysAllocString(L"");
}

delete[] wc; // Not sure if this is safe
return res;
}
----------------------------------------------------------------------

Posted by Tim Robinson on January 14th, 2004


"Boogie El Aceitoso" <frr149@telefonica.net> wrote in message
news:55ma00prtuqr9cv0r8kmqiiba5t0vefirs@4ax.com...
This is fine. SysAllocString is not allowed to touch the string passed to it
once it has returned. You know this because SysAllocString's parameter is
const. The same applies to all other const or LPCxxx parameters in other
functions.

--
Tim Robinson (MVP, Windows SDK)
http://www.themobius.co.uk/



Posted by Stephen Kellett on January 14th, 2004


In message <55ma00prtuqr9cv0r8kmqiiba5t0vefirs@4ax.com>, Boogie El
Aceitoso <frr149@telefonica.net> writes
OK, in that case, yes you should delete [] the input string that you
previously allocated.

Yes, it is.

Stephen
--
Stephen Kellett
Object Media Limited http://www.objmedia.demon.co.uk
RSI Information: http://www.objmedia.demon.co.uk/rsi.html


Similar Posts