内存泄漏 - NSData和NSMutableString

时间:2011-06-21 22:35:57

标签: ios memory nsdata memory-leaks

解析一个20MB的文件,这个文件太大,无法在2G iPod touch上一体化。我注释掉了除NSData / NSMutableString部分之外的所有代码,并且stil有泄漏。我不明白......

从文件中读取块的支持方法:

+ (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];
}

和泄密的准系统代码:

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];
}

1 个答案:

答案 0 :(得分:1)

每次进入循环时你都在alloc-init但是没有发布,所以代码中有漏洞。

NSString* xmlFragment  = [[NSString alloc] initWithBytes: [data bytes] length:[data length] encoding: NSUTF8StringEncoding];

上述陈述没有平衡release。如果你这样做,

NSString* xmlFragment  = [[[NSString alloc] initWithBytes: [data bytes] length:[data length] encoding: NSUTF8StringEncoding] autorelease];

它将在[pool drain];处取消分配。然而,循环似乎毫无意义。您可能想要更多地将xmlFragment添加到可变字符串中吗?