[xml] Freeing xpath contexts vs xml docs...

Suppose you convert a document into an xmlDoc (via
xmlParse[File,Buffer]) and then further convert it into an
xmlXPathContext (via xmlXPathNewContext) so that you can use xpath to
obtain a path to some particular node (as an xmlXPathObject) and extract
its contents or attributes.

You have to free the object.  You have to free the doc.  However, even
though there is an xmlXPathFreeContext function, I got truly bizarre
behavior if I tried to free it; immediate crashes, crashes when I later
tried to free the doc, crashes at random times when trying to execute
simple xpath evals later on.  Freeing the doc first and then the context
would immediately and consistently crash, though.  I discovered that if
I didn't free the context but did free the document, things seemed to
work (at least past the point where they crashed before:-).

The xmlXPathNewContext command does not actually say that the pointer it
returns must be freed by the caller while the other two do, so I suppose
that this was my fault, but the contiguity of the two commands (and
existence of the FreeContext command at all) does suggest that freeing a
context is possible and/or necessary at least some of the time.

Is this empirical discovery correct?  When (if ever) might one want to
free a context?

On the same line, in my application I cycle through a loop which obtains
an xml source document via socket from each of a list of hosts, parses
it into doc, transforms it to context, extracts specific tag contents
via xpath, and then tries to free all dynamically allocated resources so
that it can do the next host, and the next host and so forth "forever"
without leaking.  That's why I've tried to be careful about calling
...Free...() functions.

Is there anything else I need to do to ensure that a long term cycle of


won't leak or create other problems?  Should I periodically call e.g.
xmlInitParser or xmlCleanupParser?  It is somewhat difficult to tell
from the documentation, especially in the context of using xpath
contexts (which may or may not get cleaned up).

Sorry to be of trouble -- the application ALMOST works perfectly now
that I'm using xpath from libxml2, but the memory management thing has
eaten six hours straight and debuggers aren't very much help.


Robert G. Brown                        http://www.phy.duke.edu/~rgb/
Duke University Dept. of Physics, Box 90305
Durham, N.C. 27708-0305
Phone: 1-919-660-2567  Fax: 919-660-2525     email:rgb phy duke edu

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