c++ - 在 xmlTextReaderGetAttribute() 之后释放 xmlChar 指针

标签 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));

我的项目是在 C++ 中,但 libxml2 和所有示例来自 xmlsoft.org使用标准 C。

最佳答案

直接使用xmlFree()代替free():

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

关于c++ - 在 xmlTextReaderGetAttribute() 之后释放 xmlChar 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8437634/

相关文章:

java - 如何在 Java 中加载和使用 C DLL 中的结构和函数?

c - valgrind 显示未释放的内存

c - 基本的 C 指针分配/释放

c++ - 用于散列编译时字符串的延迟指针

c - 遍历给出段错误的字符列表

c++ - boost::exception 和 std::exception 之间的关系

c - 变量类型结构体是否必须是数组才能存储 100 个元素?

当程序在不同的地方遇到错误并退出时,C 如何释放 malloc 的内存?

c++ - 我可以检查 `shared_from_this` 是否可以安全调用吗?

c++ - 如果我创建了一个进程,是否意味着我总能终止它?