There is a memory leak in this program I am working on and it's been around for quite some time as far as the commits are concerned. According to these two explanations explanation 1 and explanation 2 whenever using the = assignment operator with _bstr_t causes a memory leak.
Context - there is a database object that is commonly used to do quick sql queries of the database. Every method eventually uses the following method
NvStatus DbUtils::ReadFromDatabase(IUnknown * poNvData,
const std::wstring & oConnectString,
const std::wstring & oSQLStatement)
{
//some checks
_bstr_t tbtSQLStr = oSQLStatement.c_str();//memory leak
_bstr_t tbtConnStr = oConnectString.c_str();//memory leak
//pass the _bstr_t to another method and get data from DB
return status;
}
According to articles this method will leak data every time it's called to query the database because of _bstr_t and how they are created. My question is what can I do to prevent the program from blowing up and force garbage collection on the _bstr_t objects?
Microsoft states that it's my responsibility to clean up the memory after using it so how can I do this without corrupting the data being passed to me? I tried doing a deep copy of the string but that failed... Any suggestions would be much appreciated!
After further investigation the two hot spots for my memory leak are the one I posted first and this one, hope this helps
static bool GetValueFromVariant(VARIANT & tvInputValue,
std::wstring & roOutputValue)
{
_bstr_t tTemp = tvInputValue.bstrVal;
if(tTemp.length()>0)
{
roOutputValue = (wchar_t*) tTemp;
}
return true;
}
Comments suggest that these _bstr_t should clean themselves up automatically... however when debugging the heap size for my windows service, the heap size increases constantly and the debugger continues to point to functions that all use these _bstr_t objects. Clearly these _bstr_t aren't being cleaned up.
More context, the majority of this memory leak stems from creating a COM object over and over again, however I am releasing the object when I am finished with it and i check the reference count returned by Release() function call, it returns 0. Therefore I know that i don't have a build up of COM objects...
Can there be an issue when pointing a wstring to the address of a _bstr_t?