我一直在互联网上搜索这个问题,这对我来说似乎很奇怪。 在我的程序中,我通过以下代码获取计算机的名称:
TCHAR ComputerName[MAX_COMPUTERNAME_LENGTH + 1];
memset( ComputerName, 0, sizeof( ComputerName ) );
DWORD dwNameLenght = MAX_COMPUTERNAME_LENGTH;
GetComputerNameW(ComputerName, &dwNameLenght);
我已经使用包含 unicode 字符的计算机名称 (ÆÆØ
) 对其进行了测试,并且工作正常(尽管 GetLastError()
返回代码 203)。
如果名称为 DESKTOP-IVHSIQD
,则无法获取计算机名称,并且 GetLastError()
返回 111,这被认为是缓冲区溢出。
操作系统是Windows 10 x64。
最佳答案
我认为您的缓冲区确实太小...GetComputerNameW
上的文档指出:
lpnSize [in, out] - On input, specifies the size of the buffer, in TCHARs. On output, the number of TCHARs copied to the destination buffer, not including the terminating null character. The lpnSize parameter specifies the size of the buffer required, including the terminating null character.
对我来说,这意味着缓冲区本身及其 lpnSize
中的大小应该足以容纳最长的计算机名称和尾随的 \0
。
您的缓冲区大小为 MAX_COMPUTERNAME_LENGTH + 1
(根据文档,这很好),但 dwNameLenght
的值少了 1 个字符。 DESKTOP-IVHSIQD
似乎也恰好是 MAX_COMPUTERNAME_LENGTH
长(15 个字符),所以我想说在附加 \0
时会发生溢出到缓冲区。将 dwNameLenght
设置为 MAX_COMPUTERNAME_LENGTH + 1
可能会解决您的问题。
关于c++ - GetComputerNameW 导致 Windows 10 中的缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33386378/