尝试清理时由于崩溃而不可避免的 libxml2 内存泄漏

un-avoidable libxml2 mem leak due to crash if cleanup attempted

我们正在使用 libxml2 来针对包含 "registered" 变量的 xmlcontext 解析 xpath。我们的析构函数尝试清理 xmlXPathContextPtr 和 xmlDocPtr:

~CLibXpathContext()
{
    xmlXPathFreeContext(m_xpathContext); //causes crash if any vars registered
    xmlFreeDoc(m_xmlDoc);
}

我们正在按如下方式注册变量:

virtual bool addVariable(const char * name,  const char * val) override
{
    if (m_xpathContext )
    {
        xmlXPathObjectPtr valx = xmlXPathWrapCString((char*)val);
        return xmlXPathRegisterVariable(m_xpathContext, (xmlChar *)name, valx) == 0;
    }
    return false;
}

libxml2清理代码如下:

void xmlXPathFreeContext(xmlXPathContextPtr ctxt) {
if (ctxt == NULL) return;

if (ctxt->cache != NULL)
    xmlXPathFreeCache((xmlXPathContextCachePtr) ctxt->cache);
    xmlXPathRegisteredNsCleanup(ctxt);
    xmlXPathRegisteredFuncsCleanup(ctxt);
    xmlXPathRegisteredVariablesCleanup(ctxt); // this is causing the issue
    xmlResetError(&ctxt->lastError);
    xmlFree(ctxt);
}

知道我可能做错了什么,或者 libxml2 代码是否有问题?

我们还尝试在调用 xmlXPathFreeContext 方法之前注销所有已注册的变量...

您必须使用 xmlXPathNewCString(const char *) 而不是 xmlXPathWrapCString(char *)。前者创建字符串的副本,而后者将字符串的所有权转移到 XPath 对象,当 XPath 对象被销毁时释放 原始字符串