Below is a simple code that i wrote about VARIANT.
The weird thing is at the end of the code, both vtEmpName and vtDept is "Accounting".

VARIANT vtEmpName;
VARIANT vtDept;
vtEmpName.vt = VT_BSTR;
vtEmpName.bstrVal = _bstr_t("Joe Schmoe");

vtDept.vt = VT_BSTR;
vtDept.bstrVal = _bstr_t("Accounting");

On the other hand, if I replace "Joe Schmoe" with "Joe", everything is ok.

Am I missing something..?

We're missing the rest of the code.

Random "memory corruption" bugs generally mean the problem could be anywhere else in the code EXCEPT the part you're staring at and the handful of lines you've posted.

A small and complete self-contained example which shows the same problem would allow us to look at the whole picture and tell you where it all starts to go wrong.

Thanks.. But that is the full code..
To duplicate the problem, just create a new project in VC++ 6.0 and paste the code and step through it..
I just tried it on a new project and the result is the same..

I read it here that say "A VARIANT that has not been initialized properly by calling VariantInit is not safe to use and can easily lead to bugs. I tried to initialize it but the result is the same."

You can't assign the variant like that because _bstr_t owns the memory.

int main()
{
_bstr_t  a = (L"Joe Schmoe");
_bstr_t b = (L"Accounting");
VARIANT vtEmpName;
VARIANT vtDept;
vtEmpName.vt = VT_BSTR;
vtEmpName.bstrVal = a.Detach();

vtDept.vt = VT_BSTR;
vtDept.bstrVal = b.Detach();
}

you can also do it like this:

int main()
{
VARIANT vtEmpName;
VARIANT vtDept;
vtEmpName.vt = VT_BSTR;
vtEmpName.bstrVal = _bstr_t(L"Joe Schmoe").Detach();

vtDept.vt = VT_BSTR;
vtDept.bstrVal = _bstr_t(L"Accounting").Detach();

}

you can also do it like this:

int main()
{
VARIANT vtEmpName;
VARIANT vtDept;
vtEmpName.vt = VT_BSTR;
vtEmpName.bstrVal = _bstr_t(L"Joe Schmoe").Detach();

vtDept.vt = VT_BSTR;
vtDept.bstrVal = _bstr_t(L"Accounting").Detach();

}

Thanks.. However, I got the following error when i tried to compile the code.

error C2039: 'Detach' : is not a member of '_bstr_t'

Btw, I'm using VC++ 6.0

Thanks.. However, I got the following error when i tried to compile the code.

error C2039: 'Detach' : is not a member of '_bstr_t'

Btw, I'm using VC++ 6.0

You are using an old compiler -- I used VC++ 2008 Express. Look in your compiler's online MSDN and see what methods _bstr_t has.

You can also do it without using _bstr_t at all. Just call SysAllocateString() -- example here.

Hmm.. The MSDN resource about _bstr_t is very limited..
Anyway, the code below seems to work.

VARIANT vtEmpName;
VARIANT vtDept;
vtEmpName.vt = VT_BSTR;
vtEmpName.bstrVal = _bstr_t(L"Joe Schmoe",FALSE);

vtDept.vt = VT_BSTR;
vtDept.bstrVal = _bstr_t(L"Accounting",FALSE);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.