Who owns returned BSTR?
Asked Answered
G

2

7

Suppose a method from a COM interface returns BSTR value. Am I right in my opinion that I must free it?

The code example at http://msdn.microsoft.com/en-us/library/aa365382(VS.85).aspx does not do that.

Who's wrong?

Gudgeon answered 16/5, 2009 at 16:51 Comment(0)
R
12

The MSDN sample is wrong. The caller frees out and in/out bstrs. If it's in/out you have to pass in null or a valid bstr. If it's out only, it doesn't have to be initialized.

It's not super clear from msdn's com allocation rules, but the client stub allocates the memory on out values so from the caller's point of view the server did. Who else can free it but the caller?

Rennet answered 16/5, 2009 at 16:54 Comment(2)
I have always found it very convenient to use _bstr_t instead of dealing with BSTR directly.Fascia
yeah, but not everyone is willing to be stuck to Visual Studio.Gudgeon
P
9

Tony is correct but I wanted to expand on his answer. The situation is not just limited to a BSTR. The caller is responsible for freeing any memory that is returned via out or in/out parameters.

Pinball answered 16/5, 2009 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.