[xml] Memory trouble with libxml.



I am using libxml to generate some xml documents for the first time, and I
am having some trouble with the library leaking memroy. I have read
through the docs, and searched through the archives, but have not figured
out what I am doing wrong. 

I am using libxml 2.4.6. Assistance would be appreciated. When I run this
program with memprof it shows that I leak about 1.7k, and that all leaks
are within the functions creating the children nodes. Could i have
compiled the library wrong, or is my code backwards in some way? My
understanding from the documentation is that the xmlFreeDoc should clean
up the whole tree, but it doesn't seem to be working.

Thanks for you assistance.

-Nick

Here is what I am doing:

#include <libxml/tree.h>
#include <libxml/parser.h>
#include <stdio.h>
#include <malloc.h>

typedef struct attribute{
  char * columnId;
  char * value;
} attribute;

typedef struct doc_part{
  char * account;
  char * xml;
} doc_part;

#define RESULT_ACCOUNT_TAG "Account"
#define ATTRIBUTES_TAG "Attributes"
#define ATTRIBUTE_TAG "Attribute"
#define COLUMN_TAG "columnId"
#define VALUE_TAG "value"
#define ID_TAG "ID"

#define NUM_ATTR 5

void express_attributes(doc_part * part,attribute * array, int count){
  int i;
  xmlDocPtr doc;
  xmlNodePtr account_node;
  xmlNodePtr attributes_node;
  xmlNodePtr attribute_node;
  xmlBufferPtr buffer;
  
  xmlInitMemory();

  buffer = xmlBufferCreate();

  doc = xmlNewDoc( "1.0" );
  /* Add the top level node. */
  account_node = xmlNewDocRawNode(doc, NULL, RESULT_ACCOUNT_TAG,NULL);
  xmlNewTextChild(account_node,NULL,ID_TAG,part->account);
  attributes_node = xmlNewChild(account_node, NULL, ATTRIBUTES_TAG,NULL);
  
  /* Add all of the attribute nodes. */
  for(i=0; i<count; i++){
    attribute_node = xmlNewChild(attributes_node,NULL,ATTRIBUTE_TAG,NULL);
    xmlNewTextChild(attribute_node,NULL,COLUMN_TAG,array[i].columnId);
    xmlNewTextChild(attribute_node,NULL,VALUE_TAG,array[i].value);
  }
  
  xmlNodeDump( buffer, doc, account_node, 0, 1 );
  part->xml = xmlStrdup(xmlBufferContent(buffer));
  xmlBufferFree( buffer );
  xmlFreeDoc( doc );
}

int main(int argc, char **argv){
  int i, column, value;
  doc_part part; 
  attribute * array = (attribute *)malloc( sizeof( attribute ) * NUM_ATTR
);
  part.account = "Some account";
  
  if( array == NULL ){
    printf( "Malloc failed." );
    return -1;
  }

  fprintf( stdout, "Check memory size now." );
  fflush( stdout );
  sleep( 10 );

  for(i=0; i<NUM_ATTR; i++){
    array[i].columnId = "column";
    array[i].value = "value";
  }
  
  express_attributes(&part,array, NUM_ATTR);

  fprintf( stdout, "Result is:\n%s", part.xml);
  
  free( part.xml );
  fprintf( stdout, "Check memory size now." );
  fflush( stdout );
  sleep( 10 );
  return 1;
}









[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]