2

我正在使用本机 CLR 托管几个星期。一开始它工作得很好。但后来我注意到我的应用程序中的某些东西会导致堆损坏。我发现这是由 CLR 启动引起的。(请参阅以下代码的简短版本。)

#pragma comment(lib, "mscoree.lib")
#include <mscoree.h>
#include <metahost.h>
#include <comdef.h>
#import "mscorlib.tlb" raw_interfaces_only          \
    high_property_prefixes("_get","_put","_putref")     \
    rename("ReportEvent", "InteropServices_ReportEvent")

using namespace mscorlib;

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr; // In fullversion used for error detection - but here unused.
    PCWSTR pszVersion = L"v4.0.30319";
    ICLRMetaHost* lpMetaHost = NULL;
    ICLRRuntimeInfo* lpRuntimeInfo = NULL;
    ICorRuntimeHost* lpRuntimeHost = NULL;
    _AppDomainPtr spAppDomain = NULL;
    BOOL bLoadable = false;
    IUnknownPtr spAppDomainThunk = NULL;

    CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&lpMetaHost);
    // After this line i can "late detect" 6 array bound heap corruptions in process memory.

    lpMetaHost->GetRuntime(pszVersion, IID_ICLRRuntimeInfo, (LPVOID *)&lpRuntimeInfo);    
    lpRuntimeInfo->IsLoadable(&bLoadable);
    lpRuntimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&lpRuntimeHost));
    lpRuntimeHost->Start();
    lpRuntimeHost->GetDefaultDomain(&spAppDomainThunk);
    spAppDomainThunk->QueryInterface(IID_PPV_ARGS(&spAppDomain));
    spAppDomainThunk->Release();
    // Now I can "late detect" up to 9 array bound heap corruptions in process memory.

    return 0;
}

Rational Purify 异常

关于如何避免这种情况的任何想法?目前在某些情况下它仍然有效,但随着我的应用程序变得越来越大,出错的机会成倍增加。

4

1 回答 1

0

虽然目视检查上面的代码并没有发现可能导致堆损坏的原因,但请尝试AppVerifier + Windbg 来检测它。以下是有关如何操作的一些信息 http://blogs.msdn.com/b/lagdas/archive/2008/06/24/debugging-heap-corruption-with-application-verifier-and-debugdiag.aspx。AppVerifier 实际上查明了堆栈(帧、调用)损坏堆的位置。

于 2012-02-29T06:42:01.950 回答