How do I assign new BSTR string to a _bstr_t that already holds an address without getting a memory leak?

Hi Expert,

I am getting memory leak with my code below.  I just want to assign a new BSTR string to a _bstr_t variable but I'm getting a memory leak report in Rational Purfify from it.  Is the Detatch method a wrong call?  What is the appropriat way to do this?  Thank you.
syUserContextPath is a _bstr_t variable and so is bstrDomainOnly

                  syUserContextPath = L"CN=SymarkGroup,CN=USERS," +  bstrDomainOnly;
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

What data type is 'syUserContextPath'?
Can you please elaborate.
Detach is opposed to Attach. This function doesn't release wrapped BSTR, it returns it to caller which is responsible to release it. Try to remove this line, I think operator= takes care about releasing previous content.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Try doing this:-
BSTR bs = syUserContextPath.Detach();
Now free the bstr called "bs":-

I guess what is happening is that you are not freeing the memory after a call to Detach().

lapuccaAuthor Commented:
As I mentioned in my posting:

syUserContextPath is a _bstr_t variable and so is bstrDomainOnly

It's my understanding that _bstr_t is a smart pointer that it manages its own memory.  I don't think that's an issue.  I just want to assign it a new BSTR string.  I do find that it seems to work that I do a Detach() before I assign the new string, otherwise my program crashes.  I don't know if this is the right way to reasign string to this type of variable.

Thank you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.