gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:17:30 26 4
gpt4 key购买 nike

我开始学习windbg,我发现了这个好帖子 How to use WinDbg to analyze the crash dump for VC++ application?

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

这样的代码怎么写?

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

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

谢谢

最佳答案

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

关于c++ - 如何编写会崩溃并生成转储文件的示例代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5028781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com