The problem is that the const XMLCh *getTextConent() function allocates memory on the document heap (using its MemoryManager), and there are no conditions that allow the caller to free memory or mark it for recycling. Thus, as soon as the returned pointer is removed from the caller's stack, the memory essentially becomes an orphan until the entire document is released, and then the MemoryManager will delete all heap allocations.
The solution is to not use getTextContent() , but instead use getNodeValue() , which returns a pointer to the data, rather than redistributing it from the internal heap.
Per this (not) error report
Aside, getTextContent does not work anyway. This is a buggy as everyone exits and is virtually useless. You cannot read the DOM in this way, otherwise you will get inaccurate data in different circumstances if there are non-adjacent text nodes (and if not, you do not need to use it in any case, since the direct value of the node will be all you need).
So, a working version of the OP example code might look like this:
#include <xercesc/dom/DOM.hpp> #include <string> XERCES_CPP_NAMESPACE_USE DOMElement *nextChildElement(const DOMElement *parent) { DOMNode *node = (DOMNode *)parent->getFirstChild(); while (node) { if (node->getNodeType() == DOMNode::ELEMENT_NODE) return (DOMElement *)node; node = node->getNextSibling(); } return nullptr; } std::string readTextNode(const DOMElement *el) { std::string sstr(""); DOMNode *node = el->getFirstChild(); if (node->getNodeType() == DOMNode::TEXT_NODE) { char *cstr = XMLString::transcode(node->getNodeValue()); sstr = cstr; XMLString::release(&cstr); } return sstr; } int main(int argc, char **argv) { XMLPlatformUtils::Initialize(); XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMLSParser *parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0); DOMDocument *doc = impl->createDocument(0, 0, 0); doc = parser->parseURI("config.xml"); DOMElement *el = doc->getDocumentElement(); // <settings> el = nextChildElement(el); // <port> el = nextChildElement(el); // <reference>Ref1</reference> // No memory leak std::string nodestr; while (1) { nodestr = readTextNode(el); // nodestr is "Ref1" } }
source share