C++之生成dmp文件,定位程序崩溃位置(Windows下)

#include 
#include 
#include 
#pragma comment(lib,"DbgHelp")

LONG WINAPI TopLevelExceptionFilter(PEXCEPTION_POINTERS pExceptInfo)
{
    SYSTEMTIME stNowTime = { 0 };
    GetLocalTime(&stNowTime);
    char szDumpFile[512] = { 0 };
    GetModuleFileName(NULL, szDumpFile, sizeof(szDumpFile));
    _snprintf(szDumpFile, sizeof(szDumpFile) - 1, "%s_%04d%02d%02d_%02d%02d%02d%03d.dmp",
        szDumpFile, stNowTime.wYear, stNowTime.wMonth, stNowTime.wDay,
        stNowTime.wHour, stNowTime.wMinute, stNowTime.wSecond, stNowTime.wMilliseconds);
    DWORD dwCurThreadId = GetCurrentThreadId();
    HANDLE hFile = CreateFile(szDumpFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile != INVALID_HANDLE_VALUE)
    {
        MINIDUMP_EXCEPTION_INFORMATION stExInfo = { dwCurThreadId, pExceptInfo, FALSE };
        HANDLE hProcess = GetCurrentProcess();
        DWORD dwProcessId = GetCurrentProcessId();
        MiniDumpWriteDump(hProcess, dwProcessId, hFile, MiniDumpNormal, &stExInfo, NULL, NULL);
        CloseHandle(hFile);
    }
    PostThreadMessage(dwCurThreadId, WM_QUIT, 0, 0);
    return EXCEPTION_EXECUTE_HANDLER;
}

int main(int argc, char** argv)
{
    SetUnhandledExceptionFilter(TopLevelExceptionFilter);
    int n = 0;
    std::cout << 1 / n;
    return 0;
}

将生成的dmp文件用VS打开,点击使用仅限本机进行调试,就会跳转到崩溃行。

  • 注意:需要保留编译时的pdb和源文件。

你可能感兴趣的:(C++之生成dmp文件,定位程序崩溃位置(Windows下))