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

C++ CRT detected that the application wrote to memory after end of heap buffer

本文关键字:结束 内存 缓冲区 检测 CRT 应用程序 c++      更新时间:2023-10-16

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

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;
                }
            }