xmlNodeGetContent memory leak, how to fix it?

156 Views Asked by At

We have code which does parsing of SOAP xml, and we use xmlNodeGetContent api. In valgrind it shows that it leaking memory. What i found in some posts that we need to explicitly free the memory returned by xmlNodeGetContent. Can someone help me on how to do this for below recursive calls?

{
while(node)
{
if(XML_ELEMENT_NODE == node->type)
{
if(0 == strcmp( soapMsgHeader.c_str() ,(const char*)node->name ) )
{
xmlNode childNode=node->children;
while(childNode)
{
if( (XML_ELEMENT_NODE == childNode->type) && ( 0 == ( xmlChildElementCount(childNode) ) ) )
{
std::string name= (const char)childNode->name;
std::string value = (const char*)xmlNodeGetContent(childNode);
soapHeaderAttributes.insert(std::pair< std::string, std::string> (name,value) );
}
childNode=childNode->next;
}
}

        if(0 == strcmp(soapMsgMo.c_str(), (const char*)node->name))
        {
            getSoapMsgMoList(node);
        }

        if(0 == strcmp(soapMsgBody.c_str(), (const char*)node->name))
        {
            node = node->children;
            while(XML_ELEMENT_NODE != node->type)
            {
                node = node->next;
            }
            msgTypeVal = (char*)node->name;
            node = node->parent;
        }
    }
    getSoapMsgDetails(node->children);
    node = node->next;
}
}```

How to fix the memory leak?
1

There are 1 best solutions below

0
nwellnhof On

You have to free the C string returned from xmlNodeGetContent with xmlFree (which typically points to free from the C library).

xmlChar *content = xmlNodeGetContent(childNode);
std::string value = (const char *) content;
xmlFree(content);