Reputation: 2780
Here is my function that is supposed to find the first encountered process with the given name and returns a handle to it. however in the process i require to allocate some data on the heap which throws an error when i try to delete.
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;
}
}
}
}
}
Upvotes: 0
Views: 790
Reputation: 75062
You shouldn't have to allocate, copy, and delete it. Also, it causes memory leak if ::strcmp(str, procName) != 0
.
Try this:
if (::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
auto length = ::GetModuleBaseName(hProcess, hMod, strBuffer, sizeof(strBuffer) / sizeof(CHAR));
if (::strcmp(strBuffer, procName) == 0)
{
return hProcess;
}
}
Upvotes: 1