V1066. The 'SysFreeString' function should be called only for objects of the 'BSTR' type.
The analyzer has detected a call of the 'SysFreeString' function on an object whose type is different from 'BSTR'.
The 'SysFreeString' function is supposed to work only with the type 'BSTR'. Breaking this rule may lead to memory deallocation issues.
Consider a simple synthetic example:
#include <atlbase.h>
void foo()
{
CComBSTR str { L"I'll be killed twice" };
// ....
SysFreeString(str); //+V1066
}
An object of type 'CComBSTR' is passed to the 'SysFreeString' function. This class is a wrapper over the 'BSTR' type and has an overloaded implicit-conversion operator 'operator BSTR()' that returns a pointer to the wrapped BSTR string. Because of that, the code above will compile correctly.
However, this code is incorrect. After the 'SysFreeString' function has freed the resource owned by the 'str' object, the object will go out of scope and its destructor will be invoked. The destructor will re-release the already freed resource, thus causing undefined behavior.
Such behavior sometimes occurs even when an object of the 'BSTR' type itself is passed to the 'SysFreeString' function. For example, PVS-Studio will report the following code:
#include <atlbase.h>
void foo()
{
CComBSTR str = { L"a string" };
BSTR bstr = str;
str.Empty();
SysFreeString(bstr); //+V1066
}
Since 'CComBSTR::operator BSTR()' returns a pointer to its own field, both objects will be owning the same resource after the 'BSTR bstr = str;' assignment. The 'str.Empty();' call will free this resource, and the subsequent call 'SysFreeString(bstr)' will attempt to free it once again.
One of the ways to avoid shared ownership is to create a copy or to use the 'CComBSTR::Detach()' method. For example, the analyzer will not report the following code:
#include <atlbase.h>
void foo()
{
CComBSTR ccombstr = { L"I am a happy CComBSTR" };
BSTR bstr1 = ccombstr.Copy();
SysFreeString(bstr1); // OK
BSTR bstr2;
ccombstr.CopyTo(&bstr2);
SysFreeString(bstr2); // OK
BSTR bstr3 = ccombstr.Detach();
SysFreeString(bstr3); // OK
}
This diagnostic is classified as:
|