Reputation: 1719
I'm trying to minimize memory leaks caused by libxml2
.
I free the xmlDoc
without problem. But when I try to free xmlNode
it causes segmentation fault. In this case, it -somehow- prevents the program from finding the file, then xmlReadFile
returns a NULL
pointer and consequently xmlDocGetRootElement
also returns a NULL
pointer and trying to accessing root_element
causes a segmentation fault
.
If I just commented out the lines with xmlFreeNode()
, everything works fine.
Just to double check, I tried to check if the node pointers are not NULL
before trying to freeing the nodes, but this doesn't help.
Why can't I free the nodes without problems?
int setKey(uint8 newState)
{
xmlDocPtr doc = NULL;
xmlNodePtr root_element = NULL;
xmlNodePtr cur_node = NULL;
char newChar[3];
const char *file = "file.xml";
doc = xmlReadFile(file, NULL, 0);
sprintf(newChar, "%d", newState);
root_element = xmlDocGetRootElement(doc);
cur_node = root_element->children; // segmentation fault
xmlNodeSetContent(cur_node, (const xmlChar *)newChar);
xmlSaveFile(file, doc);
xmlFreeDoc(doc);
if(cur_node != NULL && root_element != NULL)
{
xmlFreeNode(cur_node);
xmlFreeNode(root_element);
}
return 1;
}
Upvotes: 1
Views: 1117
Reputation: 33618
xmlFreeDoc
frees a document and all descendant nodes recursively. So freeing individual nodes again causes a double-free which typically results in a segfault. If you want to keep some of the nodes after freeing the document, you have to unlink them with xmlUnlinkNode
first.
Upvotes: 2