Re: String to VT_BSTR conversion problem
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Sun, 26 Feb 2006 11:39:34 -0500
"Karl B" <nospam@home> wrote in message
news:05k302pckg1s9lcja1sviloji51ors2i75@xxxxxxx
"Igor Tandetnik" <itandetnik@xxxxxxxx> wrote:
Karl B <nospam@home> wrote:
I'm new to COM and trying to convert an std::string into a
tagVARIANT of type VT_BSTR. I'm using an intermediate CComVariant
to achieve this, however the code appears to be causing a memory
leak. The following code demonstrates this in an exagerated fashion:
int iterations = 10000;
while(--iterations)
{
temp = str.c_str();
temp.ChangeType(VT_BSTR);
VariantCopy(&aDest, &temp);
VariantClear(&temp);
Sleep(10);
}
}
I don't see memory leaks inside the loop. The only leak is when you
fail to free aDest at the end of the loop - it still holds the last
string placed into it. What makes you think there is a major memory
leak here?
Thanks for the response. When I bring up task manager, memory usaage
reported for the above rises by a few kilobytes a second. This only
happens when compiling in Release mode. I have the final free in the
real code - missed a bit on the example.
Interesting. I see the memory grow when compiled with VC6, but not with
VC7.1. Let's dig deeper...
Got it. CComVariant::operator=(LPCSTR) uses A2COLE macro internally,
which allocates a temporary buffer on the stack using _alloca. Memory
allocated with _alloca only gets freed after the enclosing function
returns. It is a bad idea to call it in a loop - the consumed stack
space just keeps growing until stack overflow occurs.
Now, in Release build, VC6 compiler inlined CComVariant::operator= which
resulted in _alloca being called directly within your loop, hence the
memory growth.
As a workaround, move ANSI to Unicode conversion outside the loop:
std::string str("Hello Hello Hello Hello Hello Hello Hello Hello Hello
Hello ");
CComBSTR bstr = str.c_str();
and replace str.c_str() with bstr in the rest of your code. That, or
upgrade to a newer compiler where the problem is fixed.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- Follow-Ups:
- Re: String to VT_BSTR conversion problem
- From: Karl B
- Re: String to VT_BSTR conversion problem
- References:
- String to VT_BSTR conversion problem
- From: Karl B
- Re: String to VT_BSTR conversion problem
- From: Igor Tandetnik
- Re: String to VT_BSTR conversion problem
- From: Karl B
- String to VT_BSTR conversion problem
- Prev by Date: Re: String to VT_BSTR conversion problem
- Next by Date: RE: atlmincrt LNK2005 error
- Previous by thread: Re: String to VT_BSTR conversion problem
- Next by thread: Re: String to VT_BSTR conversion problem
- Index(es):
Relevant Pages
|