Skip to content

Instantly share code, notes, and snippets.

@davestevens
Created July 3, 2012 10:05
Show Gist options
  • Save davestevens/3038874 to your computer and use it in GitHub Desktop.
Save davestevens/3038874 to your computer and use it in GitHub Desktop.
Error produced by libxml2 when unlinking and linking xmlNodes from different xmlDocs and attempting to free the xmlDocs.
#include <stdio.h>
#include <libxml/parser.h>
/* compile:
gcc -m32 libxml_error.c `xml2-config --libs` `xml2-config --cflags` -Wall -Wextra -pedantic
*/
/* example xml input file
<?xml version="1.0"?>
<A>
<testNode foo="bar"/>
</A>
*/
/*
read in xml file (docA)
print this doc out (docA)
find node (nodeA) within this doc (docA)
unlink a node (nodeA) and attach it to another doc (docB)
free doc (docA)
print this doc out (docB)
free doc (docB) : This causes error :
a.out(88145) malloc: *** error for object 0x80a256: pointer being freed was not allocated
*/
int main(int argc, char *argv[]) {
xmlDoc *docA = NULL, *docB = NULL;
xmlNode *docB_root = NULL;
xmlNode *testNode = NULL;
if(argc != 2) {
fprintf(stderr, "Usage: %s <xml file>\n", argv[0]);
return -1;
}
/* read doc from xml file passed at command line */
/* FIXED: XML_PARSE_NODICT stops libxml looking after nodes */
docA = xmlReadFile(argv[1], NULL, XML_PARSE_NODICT);
if(docA == NULL) {
fprintf(stderr, "Error parsing %s\n", argv[1]);
return -1;
}
/* print out docA */
{
xmlChar *xmlbuff;
int buffersize;
xmlDocDumpFormatMemory(docA, &xmlbuff, &buffersize, 1);
printf("%s", (char *) xmlbuff);
xmlFree(xmlbuff);
}
/* find the first node in docA (ELEMENT) */
for(testNode=xmlDocGetRootElement(docA)->children;testNode;testNode=testNode->next) {
if(testNode->type == XML_ELEMENT_NODE) {
break;
}
}
/* unlink this from docA */
xmlUnlinkNode(testNode);
/* print out docA */
{
xmlChar *xmlbuff;
int buffersize;
xmlDocDumpFormatMemory(docA, &xmlbuff, &buffersize, 1);
printf("%s", (char *) xmlbuff);
xmlFree(xmlbuff);
}
/* free the doc (docA) */
xmlFreeDoc(docA);
/* even not freeing this causes error */
/* create a new doc (docB) */
docB = xmlNewDoc(BAD_CAST "1.0");
docB_root = xmlNewNode(NULL, BAD_CAST "B");
xmlDocSetRootElement(docB, docB_root);
/* link the element which was unlinked from docA */
xmlAddChild(docB_root, testNode);
/* print out docB */
{
xmlChar *xmlbuff;
int buffersize;
xmlDocDumpFormatMemory(docB, &xmlbuff, &buffersize, 1);
printf("%s", (char *) xmlbuff);
xmlFree(xmlbuff);
}
/* free docB: this causes error:
a.out(88145) malloc: *** error for object 0x80a256: pointer being freed was not allocated
*/
xmlFreeDoc(docB);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment