简体   繁体   English

我怎样才能捕获内存异常?

[英]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. Hello.exe中0x01034BB1处的未处理异常:0xC0000005:访问冲突读取位置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? 我只有一个问题:捕获的原因是什么?

This isn't a C++ exception that you can catch, it's accessing invalid memory. 这不是您可以捕获的C ++异常,它正在访问无效内存。 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. 在你的特殊情况下, pTemp可能有些问题,也许这是一个常数。 Show us the code. 告诉我们代码。

You can catch SEH exceptions using a try-except Statement . 您可以使用try-except语句捕获SEH异常 The __try and __except keywords are specific to Microsoft's compilers. __try__except关键字特定于Microsoft的编译器。

There are a few considerations, though: 但是有一些注意事项:

  • You cannot mix C++ and SEH exception handling. 您不能混合使用C ++和SEH异常处理。 The result would be undefined. 结果将是未定义的。
  • Improperly handling SEH exceptions can jeopardize process integrity. 处理不当的SEH异常会危害流程的完整性。
  • SEH exception handlers should only be used in very rare cases. SEH异常处理程序仅应在极少数情况下使用。 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. 有了这个,你应该分析问题,并修复bug。 You can use Application Verifier to easily catch memory corruption bugs. 您可以使用Application Verifier轻松捕获内存损坏错误。 You can also set up Visual Studio's debugger to break, when an SEH exception is raised ( Debug -> Windows -> Exception Settings : Win32 Exceptions ). 当引发SEH异常时,您还可以设置Visual Studio的调试器中断( Debug - > Windows - > Exception SettingsWin32 Exceptions )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM