[英]Objective-C: Potential leak of an object stored into NSDictionary
[英]Objective-C Zlib method with potential leak
我刚刚分析了我的代码,发现了一个分析错误。
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;
}
如果您的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.