gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:18:06 25 4
gpt4 key购买 nike

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

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

关于ios - 具有潜在泄漏的Objective-C Zlib方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com