I have an exception that I cannot easily replicate, but I have a very strong suspicion that it happens during VariantClear()
.
I have a function that defines a variant and then passes it off to another variant without calling VariantInit()
on it first. The called function then calls VariantClear()
on this variant, which is the likely source of the exception.
void Func1()
{
VARIANT vData;
//VariantInit(&vData); // no variant clear was done. Will adding this line stop the crash below?
Func2(vData);
}
void Func2(VARIANT& vData)
{
// some code here
VariantClear(&vData); <-- this line crashes, why??
// some code here
}
Can anyone explain why VariantClear()
could be throwing an exception? Will calling VariantInit()
in Func1()
stop this exception from happening?
CodePudding user response:
VariantClear
checks the first 16 bits of the VARIANT
to find the variant type.
Depending on the type, VariantClear
might call CoTaskMemFree
or treat the variant as a COM pointer it calls Release
on. If the type is invalid you might crash or free some unrelated memory.
If the type is VT_EMPTY
, VT_NULL
or a number type it just sets all fields to zero.
If you don't initialize the VARIANT
, the type is undefined, it could be any value left in memory from a previous operation. Therefore you must call VariantInit
first on the VARIANT
.