gpt4 book ai didi

c++ - GetComputerNameW 导致 Windows 10 中的缓冲区溢出

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:24 25 4
gpt4 key购买 nike

我一直在网上搜索这个问题,我觉得这很奇怪。在我的程序中,我通过以下代码获取计算机的名称:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com