Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my code leaking?

UPDATE2 I think I found the true source of the leaks. I had some business objects that have string properties I forgot to release. These string properties were copied from my custom xlm node object, created here (KGYXMLNode) I don't understandt why the leak is reported here instead of my custom class. My NSString properties were copy and not retain.

UPDATE: I think it was a bug in Instruments or something or it doesn't magically leak anymore, but since xcode 4 it doesn't show this leak.

Hello, according to instruments i have a leak in the following code. I've built an objective-c wrapper around certain libxml functions to be able to parse xml docs using xpath, and in this method I'm setting the innerText for my custom node object.


-(void) SetInnerTextForNode: (xmlNodePtr) node : (KGYXMLNode *) obcNode
{
  if ((node) && (node->children))
  {
    for (xmlNodePtr pnode = node->children; pnode != NULL; pnode = pnode->next)
    {
      if (pnode->type == XML_TEXT_NODE)
      {
        xmlChar *content = pnode->content;
        NSString *innerText = [[NSString alloc] initWithUTF8String: (char *)content];
        NSString *trimmedText = [innerText stringByTrimmingCharactersInSet: trimCharSet];
        if (trimmedText.length > 0)
          obcNode.innerText = trimmedText;
        [innerText release];
        break;
      }
    }
  }
}

The leak is NSString *innerText = [[NSString alloc] initWithUTF8String: (char *)content];. I don't know what is wrong.

like image 458
gyozo kudor Avatar asked Jan 25 '26 07:01

gyozo kudor


2 Answers

You shouldn't access a node's content directly, instead use xmlNodeGetContent:

        xmlChar *content = xmlNodeGetContent(pnode);
        NSString *innerText = [[NSString alloc] initWithUTF8String: (char *)content];
        NSString *trimmedText = [innerText stringByTrimmingCharactersInSet: trimCharSet];
        if (trimmedText.length > 0)
          obcNode.innerText = trimmedText;
        [innerText release];
        // you must free what xmlNodeGetContent returns!
        xmlFree(content);
        break;
like image 189
MacObserver Avatar answered Jan 26 '26 23:01

MacObserver


I don't know why your code is leaking, but it seems to me that you have an unsafe assignment of an autoreleased object to obcNode.innerText without retaining it.

like image 25
Eugene Smith Avatar answered Jan 26 '26 23:01

Eugene Smith