-1

I have a COM code where i use BSTR.

In that the application crashes when using ::SysFreeString()

However the same works in WINDOWS2003, WIN7, WINXP etc.

Any idea on what is causing the problem or what could be wrong. Sample code is as below

class CFoo::IUser 
{  
BSTR UserName; 

}
HRESULT CBar::FooMethod(VARIANT *vOut) 
{
//create interface, variant and fill the object.

BSTR bstrname = ::SysAllocString(_T("Username")); 
//use bstrname to fill interface structure.
//finished using now deallocate memory

::SysFreeString(bstrname); // crashing here only in windows 2008 R2 

}
ckv
  • 10,539
  • 20
  • 100
  • 144
  • 4
    One minor issue: whether `SysAllocString` uses wide characters or not is not controlled by the UNICODE macro, so using the `_T()` macro with it isn't correct (under normal circumstances, you should always use wide characters, and it you want to use a macro it should be `OLECHAR()`). Beyond that, we're going to have to see more code to diagnose this. Can you produce a small, compilable example that exhibits the problem? – Sven Feb 28 '12 at 12:16
  • There is nothing more in actual code. Just i will use that variable bstrname and assign it to another member variable of an interface. – ckv Feb 28 '12 at 12:17
  • But this code on its own has no problems (unless you're compiling without UNICODE, due to the macro issue I mentioned) and won't cause a crash. You can't expect us to magically divine what the actual problem is. Unless you can show us a complete example that reproduces the problem, there's nothing we can do. – Sven Feb 28 '12 at 12:20
  • @ckv, the question looks like a duplicate for [this one](http://stackoverflow.com/questions/9467004/freeing-a-bstr-using-sysfreestring-more-platform-dependant) – Igor Chornous Feb 28 '12 at 12:26
  • @kids_FoxYeah i Dont deny. But that answer didnt help me. So looking for more anwsers from experts. – ckv Feb 28 '12 at 12:31
  • 2
    Shows us the code that assigns the BSTR to the interface member, and show us how that interface stores the BSTR and uses it. Is it making a copy? Because if not, you might be using a BSTR after freeing it, and Windows caches BSTR instances so you *might* get away with that until your luck runs out (in this case, if Windows changed its caching behavior). – Sven Feb 28 '12 at 14:31

1 Answers1

3

I would suggest to stop using the raw forms like BSTR. Instead use wrapper classes like _bstr_t which encapsulates the raw BSTR pointer. The class manages resource allocation and deallocation through function calls to SysAllocString and SysFreeString and other BSTR APIs when appropriate.

More info at following link

http://msdn.microsoft.com/en-us/library/zthfhkd6%28v=vs.80%29.aspx

Ajit Vaze
  • 2,686
  • 2
  • 20
  • 24