【发布时间】:2011-08-16 08:31:23
【问题描述】:
我正在使用本地 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;
}
关于如何避免这种情况的任何想法?目前在某些情况下它仍然有效,但随着我的应用程序变得越来越大,出错的机会成倍增加。
【问题讨论】:
-
您没有检查失败,也没有将指针初始化为 NULL - 我认为完整版本的代码确实会检查错误?
-
是的,因此我使用 HRESULT,它在我的摘录中已定义但未使用。没有错误我只想让我的问题尽可能简短。我会在我的问题中注意到这一点。
-
这里的代码似乎没有错。如果您在 spAppDomainThunk->Release() 之后立即返回,是否会收到 purify 错误?
-
如代码中所述,我已经得到!6!在以下行之后净化错误:CLRCreateInstance ...。稍后通过运行应用程序,我注意到由于堆损坏异常。
-
您还没有回答问题。 ABWL 是“延迟数组边界写入”。这意味着 Purify 稍后会在对象被释放或启动泄漏扫描时检测到错误。因此,如果您在随后的代码中遇到问题,尤其是在托管部分 - 您很有可能在不相关的地方获得 ABWL。创建一个只创建托管堆并退出的项目,看看你是否看到谁的错误。
标签: c++ native clr-hosting heap-corruption