Generating Win32 Crash Dumps

Every Software Engineer knows that most software ends up crashing eventually, when it does it is very useful to have a full crash log to help you determine the cause of the problem, to that end here is a good article that I found on working on what Microsoft calls ‘Minidumps’ on windows.

http://crashrpt.sourceforge.net/docs/html/using_minidump.html

This is some code for catching unhanded exceptions (typically like null pointer references or heap corruption etc.) and writing a crash dump that can later be opened up with visual studio:

#include "DbgHelp.h"

LONG WINAPI UnhandledExceptionHandler(PEXCEPTION_POINTERS pExceptionPtrs)
{
   // This writes a dump file to the current dir.
   // To view this file open it up in Visual Studio
   // If source and symbols are available you should
   // along with the crash point.
   HANDLE hFile = CreateFileA("crash_dump.dmp",
		GENERIC_WRITE,
		0,
		NULL,
		CREATE_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL);

    MINIDUMP_EXCEPTION_INFORMATION aMiniDumpInfo;
    aMiniDumpInfo.ThreadId = GetCurrentThreadId();
    aMiniDumpInfo.ExceptionPointers = pExceptionPtrs;
    aMiniDumpInfo.ClientPointers = TRUE;

    MiniDumpWriteDump(GetCurrentProcess(),
            GetCurrentProcessId(),
            hFile,
            (MINIDUMP_TYPE) (MiniDumpWithFullMemory|MiniDumpWithHandleData),
            &aMiniDumpInfo,
            NULL,
            NULL);

    CloseHandle(hFile);

    return EXCEPTION_EXECUTE_HANDLER; 
} 

int main(int argc, char* argv[]) {

	SetUnhandledExceptionFilter(UnhandledExceptionHandler);

	// Do yer normal stuff here...

	// Crash-tastic!
	int* p = 0;
	*p = 0;
}

You will need to link to DbgHelp.lib.

If you run your program from within visual studio’s debugger (e.g. F5) then the debugger won’t let execution run on to the handler, so to test the handler you will have to run your program without the debugger (e.g. ctrl-F5), bit of an annoyance but there you have it…