I’m building a statistics monitor application and I’m using a XML parser to retrieve my data.
After a lot of research, learning and reading about the memory management and retainCount, etc. of obj-c but I still encounter memory leaks in Instruments.
for(int counter = 0; counter < [resultElement childCount]; counter++) { //Loop trough the childs
//Instruments Leaks tells me that I have 75% leaks here
[entryItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
}
//Instruments Leaks tells me that I have 25% leaks here
[totalEntries addObject:[entryItem copy]]; //Copy it into the MutableArray
The memory leaks occur in the XML parser but I don’t know how to fix the leak.
- (NSString *)stringValue {
if (_node->type == XML_TEXT_NODE || _node->type == XML_CDATA_SECTION_NODE){
return [NSString stringWithUTF8String:(const char *)_node->content]; //16.7% leaking
}
if (_node->type == XML_ATTRIBUTE_NODE){
return [NSString stringWithUTF8String:(const char *)_node->children->content]; //50.0% leaking
}
NSMutableString *theStringValue = [[[NSMutableString alloc] init] autorelease];
for (CXMLNode *child in [self children]) {
[theStringValue appendString:[child stringValue]]; //33.3% leaking
}
return theStringValue;
}
In the line
you copy the object (hence your new object has a retain count of one), and add it to totalEntries, which again increases the retain count. You’re missing a release. Should be
or
You can use the static analyzer to get some insight into this. And with ARC coming, you’ll soon needn’t worry about this at all (although it is useful to gain some understanding of it anyway).