这是我的函数,它应该找到具有给定名称的第一个遇到的进程并返回一个句柄。但是在这个过程中我需要在堆上分配一些数据,当我尝试删除时会抛出错误。
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;
}
}
}
}
}
答案 0 :(得分:1)
您不必分配,复制和删除它。此外,如果::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;
}
}