4

我开发了下一个用于将 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)' 来释放对象,那么我的功能将变得毫无用处......任何帮助我将不胜感激

4

2 回答 2

7

你需要free字节,因为NSData它不拥有它的所有权:它不知道数组是临时的还是动态的,所以它会复制它。

要解决此问题,请更换

return [NSData dataWithBytes:bytes length:c];

NSData *res = [NSData dataWithBytes:bytes length:c];
free(bytes);
return res;
于 2013-08-06T18:16:55.657 回答
0

代替

return [NSData dataWithBytes:bytes length:c];

return [NSData dataWithBytesNoCopy:bytes length:c];

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

于 2019-11-16T01:55:03.743 回答