Q:

Issue with new/delete with SecureZeroMemory

Can anyone help me understand why my code is failing on delete[] szPassword in the first block of code? I know that szPassword is only copying "a", and st2 is equal to 8:
TCHAR *szPassword = new TCHAR[2]();
StringCchCopy(szPassword, 2, L"ab");
SIZE_T st2 = sizeof(szPassword);
SecureZeroMemory(szPassword, st2);
delete[] szPassword;

However, when this is run, without getting the sizeof() value, it works fine:
TCHAR *szPassword = new TCHAR[2]();
StringCchCopy(szPassword, 2, L"ab");
SecureZeroMemory(szPassword, 2);
delete[] szPassword;

A:

szPassword is a pointer, not an array and therefore sizeof(szPassword) will be 4 or 8. In a 64-bit application this is too much, you will attempt to write 8 bytes to a 4 byte buffer.
The C++ run-time is allowed to allocate more than you ask it to and it often does this so it can add special data to the end of the buffer so it can detect buffer overruns.
Do something like this instead:
const UINT charcount = 2;
TCHAR *szPassword = new TCHAR[charcount];
...
SecureZeroMemory(szPassword, charcount * sizeof(TCHAR));
delete[] szPassword;

If the buffer is always small-ish you can just use an array on the stack:
TCHAR szPassword[200];
...
SecureZeroMemory(szPassword, sizeof(szPassword));

