login about faq

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.

asked Jan 26 '15 at 09:33

chilkat's gravatar image

chilkat ♦♦

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|*");


answered Jan 26 '15 at 09:47

chilkat's gravatar image

chilkat ♦♦

Another alternative to avoid having to manually delete the pointer returned from xmlRoot->GetChildWithTag("CmdResponse") is to convert it into a unique_ptr<ckxml> (or other smart pointer).

(Jan 28 '15 at 04:04) roan98dk
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or __italic__
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported



Asked: Jan 26 '15 at 09:33

Seen: 2,819 times

Last updated: Jan 28 '15 at 04:04

powered by OSQA