如何编写会崩溃并生成转储文件的示例代码?

How to write a sample code that will crash and produce dump file?(如何编写会崩溃并生成转储文件的示例代码?)

本文介绍了如何编写会崩溃并生成转储文件的示例代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习windbg,发现这篇好文章如何使用WinDbg分析崩溃转储 VC++ 应用程序?

I started learned windbg and I found this good post How to use WinDbg to analyze the crash dump for VC++ application?

现在我要按照说明一步一步来.问题来了:我需要编写一些可以立即崩溃的示例代码,并创建一些可以被windbg使用的转储文件.

Now I want to follow the instructions and do it step by step. Here is the problem: I need to write some sample code that can immediately crash, and create some dump files that can be used by windbg.

这样的代码怎么写?

void Example4()
{
    int* i = NULL;
    *i = 80;
}

上面的代码会立即崩溃;但是,我不知道在哪里可以找到转储文件?

The above code will crash immediately; however, I don't know where to find the dump file?

谢谢

推荐答案

#include <Windows.h>
#include <Dbghelp.h>

void make_minidump(EXCEPTION_POINTERS* e)
{
    auto hDbgHelp = LoadLibraryA("dbghelp");
    if(hDbgHelp == nullptr)
        return;
    auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
    if(pMiniDumpWriteDump == nullptr)
        return;

    char name[MAX_PATH];
    {
        auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH);
        SYSTEMTIME t;
        GetSystemTime(&t);
        wsprintfA(nameEnd - strlen(".exe"),
            "_%4d%02d%02d_%02d%02d%02d.dmp",
            t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
    }

    auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    if(hFile == INVALID_HANDLE_VALUE)
        return;

    MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
    exceptionInfo.ThreadId = GetCurrentThreadId();
    exceptionInfo.ExceptionPointers = e;
    exceptionInfo.ClientPointers = FALSE;

    auto dumped = pMiniDumpWriteDump(
        GetCurrentProcess(),
        GetCurrentProcessId(),
        hFile,
        MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory),
        e ? &exceptionInfo : nullptr,
        nullptr,
        nullptr);

    CloseHandle(hFile);

    return;
}

LONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e)
{
    make_minidump(e);
    return EXCEPTION_CONTINUE_SEARCH;
}

int main()
{
    SetUnhandledExceptionFilter(unhandled_handler);

    return *(int*)0;
}

这篇关于如何编写会崩溃并生成转储文件的示例代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何编写会崩溃并生成转储文件的示例代码?

基础教程推荐