1

I have just analyzed my code and found a analysis error.

Potential leak of memory pointed to by 'decompressedBytes'

I have never had such an error, I have done some hunting around but cannot figure out how to fix this "potential leak".

This is what my code looks like

- (NSData*) dataByDecompressingData:(NSData*)data{
    Byte* bytes = (Byte*)[data bytes];
    NSInteger len = [data length];
    NSMutableData *decompressedData = [[NSMutableData alloc] initWithCapacity:COMPRESSION_BLOCK];
    Byte* decompressedBytes = (Byte*) malloc(COMPRESSION_BLOCK);
    
    z_stream stream;
    int err;
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.opaque = (voidpf)0;
    
    stream.next_in = bytes;
    err = inflateInit(&stream);
    CHECK_ERR(err, @"inflateInit");
    
    while (true) {
        stream.avail_in = len - stream.total_in;
        stream.next_out = decompressedBytes;
        stream.avail_out = COMPRESSION_BLOCK;
        err = inflate(&stream, Z_NO_FLUSH);
        [decompressedData appendBytes:decompressedBytes length:(stream.total_out-[decompressedData length])];
        if(err == Z_STREAM_END)
            break;
        CHECK_ERR(err, @"inflate");
    }
    
    err = inflateEnd(&stream);
    CHECK_ERR(err, @"inflateEnd");
    
    free(decompressedBytes);
    return decompressedData;
}
4

1 回答 1

4

如果您CHECK_ERR碰巧是这样if (err) return nil的,则警告意味着您的函数已提前返回,并且可能并不总是释放您malloc编辑的内存

malloc如果可能的话,你应该避免。

尝试这个

NSMutableData *decompressedBytesData = [[NSMutableData alloc] initWithCapacity:COMPRESSION_BLOCK]; // autorelease if not ARC
Byte* decompressedBytes = (Byte*)[decompressedBytesData mutableBytes];

// you don't need free(decompressedBytes);
于 2013-10-30T01:19:31.273 回答