【问题标题】:Objective-C Zlib method with potential leak具有潜在泄漏的 Objective-C Zlib 方法
【发布时间】:2013-10-30 01:09:13
【问题描述】:

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

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

【问题讨论】:

  • @Kevin 是 malloced 内存,与 ARC 无关。 @HurkNburkS CHECK_ERR 是什么?它会提前返回吗?
  • 你没有自动释放 decompressedData
  • Xcode 会给你它计算出的可能泄漏的路径。它显示了什么?
  • 检查return的CHECK_ERR
  • 抱歉回复晚了,我试图弄清楚自己发生了什么。但是@Bryan 的回答确实有效。谢谢你们的帮助。

标签: ios iphone objective-c byte zlib


【解决方案1】:

如果您的 CHECK_ERR 恰好是 if (err) return nil 之类的东西,则警告意味着您的函数已提前返回,并且可能并不总是释放您 malloced 的内存

如果可能,您应该避免使用malloc

试试这个

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

// you don't need free(decompressedBytes);

【讨论】:

  • 是的,谢谢。对不起,我正在调试试图找出问题出在我自己的迟到回复:P
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 2011-02-07
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多