c++builder-xe2

Invalid Pointer Operation TXMLDocument


I am having some problems with an application. It used to work just fine but today when i ran it again to test it a bit more I got some Invalid Pointer Operation exceptions.

This is some part of the code: Here I declare:

TXMLDocument *xml;

And a few lines below I construct it:

xml = new TXMLDocument(NULL);

And then a few lines below the construction I am loading the xml and then trying to access the root node named "root":

xml->LoadFromXML(AnsiString(final_xml.c_str()));

//at the line below i am getting the Invalid Pointer Operation exception.
_di_IXMLNodeList root = xml->ChildNodes->GetNode("root")->GetChildNodes();

At the end of the function I am deleting the xml:

delete xml;

Here you can find the whole function: http://pastebin.com/MpRf8Gfn

The strange thing is that it used to work find and now I am getting this error out from nowhere (I have changed nothing in the source code for about a month and it used to work fine).

If anyone has any idea why would this error pop up I would be grateful. Thanks in advance.


Solution

  • If you read the documentation, creating a TXMLDocument instance with a NULL owner causes it to act like a reference counted interfaced object instead of a normal object. As such, you need to follow proper reference counting semantics, which you are not doing, hence the crashing.

    The best way to do that in this situation is to use LoadXMLData() and _di_IXMLDocument, eg:

    void __fastcall TForm1::dataUpload2ServerServe(TCustomIpClient *ClientSocket)
    {
        _di_IXMLDocument xml;
        ...
        xml = LoadXMLData(final_xml.c_str());
        _di_IXMLNodeList root = xml->DocumentElement->ChildNodes;
        ...
        xml->SaveToFile(filename);
        ...
    }
    

    When the xml and root variables go out of scope, they will automatically decrement the reference counts for you. If you want to "free" them manually, you can simply assign NULL to them:

    root = NULL;
    xml = NULL;
    

    Or call their Release() method:

    root.Release();
    xml.Release();