在xmlTextReaderGetAttribute()之后释放xmlChar指针

Joh*_*ohn 0 c c++ free libxml2

我之前成功使用xmlTextReaderGetAttribute(来自xmlsoft.org),但API文档要求我释放返回的内容xmlChar*.现在我的应用程序在第二次(第一次传递null)调用时崩溃free(),如下所示:

xmlTextReaderPtr reader = null;
xmlChar *attribVal = null;
//blah...
if (xmlTextReaderAttributeCount(reader) > 0) {
    free((attribVal));

attribVal = xmlTextReaderGetAttribute(reader, (const xmlChar*)"super-Attrib");
if (xmlStrcasecmp(attribVal, (const xmlChar*)"monoMega-Attrib") == 0) {
    free((attribVal));
Run Code Online (Sandbox Code Playgroud)

我的项目是用C++ 编写的,但是libxml2和xmlsoft.org的所有例子使用标准C.

Rem*_*eau 6

使用xmlFree()而不是free()直接:

xmlTextReaderPtr reader = null; 
xmlChar *attribVal = null; 
//blah... 
if (xmlTextReaderAttributeCount(reader) > 0)
{ 
    attribVal = xmlTextReaderGetAttribute(reader, BAD_CAST "super-Attrib"); 
    if (attribVal)
    {
        ...
        xmlFree(attribVal);
    }
} 
Run Code Online (Sandbox Code Playgroud)