0
    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?)

YU lee
  • 13
  • 2
  • 1
    Be interesting if you can safely catch that. Usually such mistakes are the result of a much earlier fatal programming mistake and it's long since too late to correct whatever other damage that's already been done by the mistake and wasn't caught. Better you let the program crash than allow it to proceed and give a faulty result. – user4581301 Dec 09 '22 at 02:07
  • i want do something in __except block, (ex logging, dump, etc...) not skip – YU lee Dec 09 '22 at 02:11

1 Answers1

1

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

Axalo
  • 2,953
  • 4
  • 25
  • 39
  • Is it possible convert such exceptions into C++ ones? We can do it for structured ones. – Evg Dec 09 '22 at 03:19
  • 2
    @Evg I believe there is not. A heap corruption is a fatal error that shouldn't happen in the first place. Continuing execution and passing C++ exceptions around is dangerous. It's best to just dump the stack and terminate the program. – Axalo Dec 09 '22 at 03:54