2013-10-30 20 views
1

我剛剛分析了我的代碼,發現分析錯誤。具有潛在泄漏的Objective-C 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; 
} 

任何幫助將不勝感激

+0

是否使用ARC? – Kevin

+1

@Kevin它是'malloc'ed內存,與ARC無關。 @HurkNburkS什麼是CHECK_ERR?它是否提前回報? –

+0

你沒有autorelease解壓縮數據 –

回答

4

如果你的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); 
+0

是的,這工作謝謝你。對不起,我正在調試後期回覆,試圖找出問題出在哪裏:P – HurkNburkS