0

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*
Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51

2 Answers2

6

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.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • In addition, be careful not to confuse "freeing the memory" with "destroying its contents"; one does not imply the other. – andlabs Mar 02 '16 at 16:20
  • @and Is that just a general statement? Because we're talking about strings here, and characters are fundamental types that don't need to be destroyed. – Cody Gray - on strike Mar 02 '16 at 16:21
  • Destroying in the literal sense; the freeing process isn't guaranteed to overwrite the characters with random garbage, nor is it even required to return the memory to the OS so attempting to access it again would fault. – andlabs Mar 02 '16 at 18:16
  • Thanks for the answers. My intention was about the "destroying its content" – Karthik Tadikonda Mar 03 '16 at 04:48
  • If you want to destroy its content, @user, call `ZeroMemory` on the buffer *before* freeing it. But there's really no point, that's why it isn't done automatically. – Cody Gray - on strike Mar 03 '16 at 10:59
0

In this particular case of releasing BSTR is does not necessary free it, you are correct, it's not about not zeroing it or being undefined behavior. BSTR allocations are cached, so when you do SysFreeString() allocated block does not immediately go away, it stays cached for later use. This is controlled by OANOCACHE variable and SetOaNoCache function.

bunglehead
  • 1,104
  • 1
  • 14
  • 22