Search code examples
c++winapivisual-c++com

SysFreeString is not freeing the variable


Could anyone help me in understanding why the below code is not freeing the memory after it is being allocated.

BSTR ys;
{
    ys = ::SysAllocString(L"Asdfghjk");
    {
        ::SysFreeString(ys);
    }
}
wcout << ys; // *I could see "Asdfghjk" in console window*

Solution

  • It is freeing the memory, but it is not zeroing it out, so it just so happens that it still contains its previous value.

    Your use of the memory after it has been freed (in the call to wcout) is undefined behavior. It appears to work, but only by accident.