John S.
John S.

Reputation: 27

How can I catch a memory exception?

I'm having an issue catching an exception , this is the error:

Unhandled exception at 0x01034BB1 in Hello.exe: 0xC0000005: Access violation reading location 0x02343DA2.

This is my code:

bool VerifyAddress(HANDLE hwnd, DWORD dwAddress, char* bMask, char *szMask )
{
    PBYTE *pTemp = { 0 };

    for ( int i = 0; *szMask; ++szMask, ++bMask, ++i )
    {

        try {
            if ( !ReadProcessMemory( hwnd, reinterpret_cast<LPCVOID>(dwAddress + i), &pTemp, sizeof(pTemp), 0 ) ){
                failedRPM++;
                return false;
            }
        } catch(...) {
            failedRPM++;
            return false;
        }

        if ( *szMask == 'x' && reinterpret_cast<char*>(pTemp) != reinterpret_cast<char*>(*bMask)){
            failedMask++;
            return false;
        }
    }
    return true;
}

DWORD FindPattern(HANDLE hwnd, char* bMask, char *szMask )
{
    for ( DWORD dwCurrentAddress = 0x015A1DB4; dwCurrentAddress < 0x7FFFFFF; dwCurrentAddress++ ){
        if ( VerifyAddress( hwnd, dwCurrentAddress, bMask, szMask )) {
            return dwCurrentAddress;
        }
    }
    return 0x0;
}

I have just a question: why the catch is not catching?

Upvotes: 1

Views: 1750

Answers (2)

IInspectable
IInspectable

Reputation: 51414

You can catch SEH exceptions using a try-except Statement. The __try and __except keywords are specific to Microsoft's compilers.

There are a few considerations, though:

  • You cannot mix C++ and SEH exception handling. The result would be undefined.
  • Improperly handling SEH exceptions can jeopardize process integrity.
  • SEH exception handlers should only be used in very rare cases. In your specific case it will probably hide a bug lingering elsewhere.

With that out of the way, you should probably analyze the issue, and fix the bug. You can use Application Verifier to easily catch memory corruption bugs. You can also set up Visual Studio's debugger to break, when an SEH exception is raised (Debug -> Windows -> Exception Settings: Win32 Exceptions).

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182769

This isn't a C++ exception that you can catch, it's accessing invalid memory. There's no guarantee that the process is in a sane state for catching anything.

In your particular case, something's probably wrong with pTemp, maybe it's a constant. Show us the code.

Upvotes: 2

Related Questions