Parsing a 20MB file that is too large to do in one piece on a 2G iPod touch. I commented out all code except the NSData/NSMutableString part and stil have the leak. I don’t understand….
support method to read chunk from file:
+ (NSData *) dataWithContentsOfFile:(NSString *)path atOffset:(off_t)offset withSize:(size_t)bytes {
FILE *file = fopen([path UTF8String], "rb");
if(file == NULL)
return nil;
void *data = malloc(bytes); // check for NULL!
fseeko(file, offset, SEEK_SET);
fread(data, 1, bytes, file); // check return value, in case read was short!
fclose(file);
// NSData takes ownership and will call free(data) when it's released
return [NSData dataWithBytesNoCopy:data length:bytes];
}
and the barebones code that leaks:
while( cnt<total) {
NSAutoreleasePool* pool= [[NSAutoreleasePool alloc] init];
NSData* data= [NSData dataWithContentsOfFile:fullPath atOffset:cnt withSize:MIN(100000,total-cnt)];
NSString* xmlFragment = [[NSString alloc] initWithBytes: [data bytes] length:[data length] encoding: NSUTF8StringEncoding];
cnt+= [xmlFragment length];
[pool drain];
}
You are doing
alloc-initevery time you are in the loop but there isn’t a release so there is a leak in your code.There is no balancing
releasefor the statement above. If you do,It will be deallocated at
[pool drain];. However the loop seems pointless. You probably meant to do a bit more like addxmlFragmentto a mutable string perhaps?