如何在iOS中正确释放内存:永远不会释放内存;

问题描述 投票:3回答:2
指出的潜在的内存泄漏

我开发了下一个代码,用于将NSMutableString对象转换为NSData对象:

-(NSData *)desSerializarFirma:(NSMutableString *)firma{

    NSArray *arregloBits    = [firma componentsSeparatedByString:@","];
    unsigned c              = arregloBits.count;
    uint8_t *bytes          = malloc(sizeof(*bytes) * c);

    unsigned i;
    for (i = 0; i < c; i ++)
    {
        NSString *str = [arregloBits objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = (uint8_t)byte;
    }

    return [NSData dataWithBytes:bytes length:c];
}

当我用xCode分析它时说

memory is never released; potential leak of memory pointed to by 'bytes'

此语句指向我的代码的最后一行:

return [NSData dataWithBytes:bytes length:c];

如果我通过执行'free(bytes)'释放对象,那么我的函数将变得无用……任何帮助,我将不胜感激

ios xcode memory-management memory-leaks
2个回答
7
投票

您需要free个字节,因为NSData不拥有它的所有权:它不知道该数组是临时的还是动态的,因此它对其进行了复制。

要解决此问题,请替换

return [NSData dataWithBytes:bytes length:c];

with

NSData *res = [NSData dataWithBytes:bytes length:c];
free(bytes);
return res;

0
投票

替换

return [NSData dataWithBytes:bytes length:c];

with

return [NSData dataWithBytesNoCopy:bytes length:c];

然后,NSData会获得字节的所有权,并将为您释放它们。

© www.soinside.com 2019 - 2024. All rights reserved.