Home > Back-end >  how to catch or __except when double free runtime error (HeapAlloc)
how to catch or __except when double free runtime error (HeapAlloc)

Time:12-11

    HANDLE h = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 1024, 4096);
    int* test = (int*)HeapAlloc(h, HEAP_GENERATE_EXCEPTIONS, sizeof(int));
    __try {
        HeapFree(h, 0, ((char*)test));
        HeapFree(h, 0, ((char*)test));
    }
    __except (EXCEPTION_EXECUTE_HANDLER)
    {
        cout << "i want to get here";
    }

new / delete can print message, why HeapAlloc is not? ( how to handle HeapAlloc double free error?)

CodePudding user response:

Structured Exception Handling doesn't work in this case.
Minimal example using a Vectored exception handler:

#include <Windows.h>

LONG NTAPI ExceptionHandler(PEXCEPTION_POINTERS p)
{
    switch (p->ExceptionRecord->ExceptionCode)
    {
    case STATUS_HEAP_CORRUPTION:
        // Do stuff

        /* Continuing after this can be dangerous.
           It is better to return EXCEPTION_CONTINUE_SEARCH
           or directly terminate the program. */
        return EXCEPTION_CONTINUE_EXECUTION;
    }

    return EXCEPTION_CONTINUE_SEARCH;
}

int main()
{
    AddVectoredExceptionHandler(0, ExceptionHandler);

    HANDLE h = HeapCreate(0, 1024, 4096);
    LPVOID pv = HeapAlloc(h, 0, 42);
    HeapFree(h, 0, pv);
    HeapFree(h, 0, pv);

    return 0;
}

Additional information

  • Related