具有潜在泄漏的Objective-C Zlib方法

时间:2013-10-30 01:09:13

标签: ios iphone objective-c byte zlib

我刚刚分析了我的代码并发现了分析错误。

Potential leak of memory pointed to by 'decompressedBytes'

我从来没有遇到过这样的错误,我已经做了一些狩猎,但无法弄清楚如何解决这个“潜在的泄漏”

这就是我的代码看起来像

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分: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);