Mangled LPCTSTR string returned from a function

484 views Asked by At

I have two projects, A and B

Project A is compiled with:
1. Standard Windows Libraries
2. Multi-byte character set
3. NO common language support

Project B is compiled with:
1. MFC as a dynamic dll
2. Multi-byte character set
3. WITH using common language support

The following function is defined in project A:

LPCTSTR CAppProxy::DriverName(IDriverAgent *driver)  
{  
  BSTR bstr;  
  HRESULT hr = driver->get_Name(&bstr);  
  CString str = CString(bstr);  
  return(str);  

}

and is called from project B using:

CString name = appProxy->DriverName(driver);

but when driver name is called, the contents of "name" are garbage

1

There are 1 answers

2
Mark Ransom On BEST ANSWER

A classic mistake, you're returning a pointer to a local object which reaches the end of its lifetime at the end of the function. The stack containing the string is released and overwriten with random stuff.

More specifically, you're returning a pointer to a data structure inside the CString object which is invalidated when the CString is destroyed.

If both projects are using the same version of CString you could return one of those instead of LPCTSTR.