gpt4 book ai didi

C++ CRT 检测到应用程序在堆缓冲区结束后写入内存

转载 作者:行者123 更新时间:2023-11-28 06:03:12 29 4
gpt4 key购买 nike

这是我的函数,它应该找到第一个遇到的具有给定名称的进程并返回它的句柄。然而在这个过程中我需要在堆上分配一些数据,当我尝试删除时会抛出错误。

HANDLE GetProcessHandleByName(CHAR procName[])
{
DWORD pProcessIds[1024];
DWORD pBytesReturned;
::EnumProcesses(pProcessIds, sizeof(pProcessIds), &pBytesReturned);
int noOfProcs = pBytesReturned / sizeof(DWORD);
if (noOfProcs)
{
for (int i = 0; i < noOfProcs; i++)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, pProcessIds[i]);
if (!hProcess) continue;
HMODULE hMod;
DWORD cbNeeded;
CHAR strBuffer[MAX_PATH];
if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
auto length = ::GetModuleBaseName(hProcess, hMod, strBuffer, sizeof(strBuffer) / sizeof(CHAR));
CHAR *str = new CHAR[length];
::strcpy(str, strBuffer);
if (::strcmp(str, procName) == 0)
{
delete[] str; //can't delete -> Exception CRT detected that the application wrote to memory after end of heap buffer.
return hProcess;
}
}
}
}
}

最佳答案

您不必分配、复制和删除它。此外,如果 ::strcmp(str, procName) != 0 会导致内存泄漏。

试试这个:

            if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
auto length = ::GetModuleBaseName(hProcess, hMod, strBuffer, sizeof(strBuffer) / sizeof(CHAR));
if (::strcmp(strBuffer, procName) == 0)
{
return hProcess;
}
}

关于C++ CRT 检测到应用程序在堆缓冲区结束后写入内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878596/

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