XercesDOMParser* and DOMDocument* going out of scope before a DOMElement*

StackOverflow https://stackoverflow.com/questions/17407463

  •  02-06-2022
  •  | 
  •  

質問

Short Version: Is it safe for a XercesDOMParser* and DOMDocument* to go out of scope before a DOMElement* that they were used to create does?

Long version:

In the code snippet below I create a local XercesDOMParser* and DOMDocument* in order to get the root element of the document and store it in a member DOMElement* variable. The XercesDOMParser* and DOMDocument* both go out of scope at the end of the constructor, but the DOMElement* lives on as a member variable. Is this ok? So far it seems to work but I am nervous that I may have problems later.

JNIRequest::JNIRequest(JNIEnv *env, jobject obj, jstring input)
{
    char *szInputXML = (char*) env->GetStringUTFChars(input, NULL);
    XMLPlatformUtils::Initialize();
    XercesDOMParser* pParser = new XercesDOMParser();
    XMLByte* xmlByteInput = (XMLByte*) szInputXML;
    xercesc::MemBufInputSource source(xmlByteInput, strlen(szInputXML), "BufferID");
    pParser->parse(source);
    DOMDocument* pDocument = pParser->getDocument();
    /* This next variable is a DOMElement* */
    this->_pRootElement = pDocument->getDocumentElement();  
}
役に立ちましたか?

解決

Your code snippet looks like it is creating some memory leaks. I'm afraid this is also the reason why the code seems to "work" for the moment.

In general the Xerces parser owns the document tree. Please take a look at AbstractDOMParser::adoptDocument() to transfer the ownership away from the parser. This means for your code example, if you would correctly release the parser, the document is also deleted making your pointer to the DOMElement invalid.

The solution would be to call adoptDocument() and save the pointer to the Document Element afterwards. Please note that you need to release the node tree (on closing the application?) and that the tree could consume a lot of memory depending on the size of the XML ...

Hope this helps

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top