如何在iOS中正确释放内存:永远不会释放内存;潜在的内存泄漏指向

时间:2022-09-05 18:51:32

I have the next code developed for converting an NSMutableString object into NSData object:

我有下一个代码,用于将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];
}

when I analyze this with xCode it says

当我用xCode分析它时,它说

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

this statement points to the last line of my code:

这句话指向我代码的最后一行:

return [NSData dataWithBytes:bytes length:c];

if I release the object by executing 'free(bytes)' then I get my function useless... any help I'll appreciate

如果我通过执行'free(bytes)'释放对象,那么我的功能无用......任何帮助我都会感激

1 个解决方案

#1


7  

You need to free the bytes, because NSData does not take ownership of it: it cannot know if the array is a temporary or a dynamic, so it makes a copy of it.

你需要释放字节,因为NSData没有获得它的所有权:它无法知道数组是临时的还是动态的,因此它会复制它。

To fix this problem, replace

要解决此问题,请替换

return [NSData dataWithBytes:bytes length:c];

with

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

#1


7  

You need to free the bytes, because NSData does not take ownership of it: it cannot know if the array is a temporary or a dynamic, so it makes a copy of it.

你需要释放字节,因为NSData没有获得它的所有权:它无法知道数组是临时的还是动态的,因此它会复制它。

To fix this problem, replace

要解决此问题,请替换

return [NSData dataWithBytes:bytes length:c];

with

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