我刚刚分析了我的代码,发现了一个分析错误。
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
ed的内存
您应尽可能避免使用malloc
。
尝试这个
NSMutableData *decompressedBytesData = [[NSMutableData alloc] initWithCapacity:COMPRESSION_BLOCK]; // autorelease if not ARC
Byte* decompressedBytes = (Byte*)[decompressedBytesData mutableBytes];
// you don't need free(decompressedBytes);