Archived Forum Post

Index of archived forum posts


XML memory leak? (in C++)

Jan 28 '15 at 04:04

Can you tell me why this causes a memory leak:

       CkXml xml;
       CkXml* xmlRoot = 0;
       xmlRoot = xml.GetRoot();
       CString sResponse = xmlRoot->GetChildWithTag("CmdResponse")->GetChildWithTag("ResponseOrigin")->content();
       delete xmlRoot;

and the following doesn’t?

       CkXml xml;
       CkXml* xmlRoot = 0;
       xmlRoot = xml.GetRoot();
       //CString sResponse = xmlRoot->GetChildWithTag("CmdResponse")->GetChildWithTag("ResponseOrigin")->content();

delete xmlRoot;

I am using CkSettings::cleanupMemory(); to make sure. I am very puzzled.


Any Chilkat C++ method that returns a pointer to a Chilkat object is such that the object returned must be deleted by the application. For example:

CkXml *pChild = xmlRoot->GetChildWithTag("CmdResponse");
delete pChild;
In the 1st code snippet above, the calls to GetChildWithTag are returning objects which are not being deleted. Also, it is dangerous to write code such as this:
...   xmlRoot->GetChildWithTag("CmdResponse")->GetChildWithTag("ResponseOrigin")->content();
If your app is presented with incorrect data, and if the GetChildWithTag methods return null, then the code will crash. It's better to break this up into individual lines of code. For example:
// Use the "2" method to update the internal referece of the CkXml object (instead of returning a new CkXml object)
CString sResponse = "";
if (xmlRoot->GetNthChildWithTag2("CmdResponse",0)) 
    sResponse = xmlRoot->GetChildContent("ResponseOrigin");
    // Restore the internal reference.

Alternatively, the CkXml::ChilkatPath method could be used to get the content in one step:

CString sRepsonse = xmlRoot->ChilkatPath("CmdRepsonse|ResponseOrigin|*");