简体   繁体   English

使用SecureZeroMemory新建/删除问题

[英]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? 谁能帮助我理解为什么我的代码在代码的第一部分中的delete [] szPassword失败? I know that szPassword is only copying "a", and st2 is equal to 8: 我知道szPassword仅复制“ a”,并且st2等于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: 但是,当运行此命令时,如果没有获取sizeof()值,则可以正常工作:

TCHAR *szPassword = new TCHAR[2]();
StringCchCopy(szPassword, 2, L"ab");
SecureZeroMemory(szPassword, 2);
delete[] szPassword;

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. szPassword是一个指针,而不是一个数组,因此sizeof(szPassword)将为4或8。在64位应用程序中,这太多了,您将尝试将8个字节写入4个字节的缓冲区。

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. C ++运行时可以分配超出您要求的数量,而且它经常这样做,因此它可以在缓冲区的末尾添加特殊数据,从而可以检测缓冲区溢出。

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM