How to release correctly memory in iOS: Memory is never released; potential leak of memory pointed to by

£可爱£侵袭症+ 提交于 2019-12-22 09:02:16

问题


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

-(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

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


回答1:


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.

To fix this problem, replace

return [NSData dataWithBytes:bytes length:c];

with

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



回答2:


Replace

return [NSData dataWithBytes:bytes length:c];

with

return [NSData dataWithBytesNoCopy:bytes length:c];

then NSData takes ownership if the bytes and will free them for you.



来源:https://stackoverflow.com/questions/18087510/how-to-release-correctly-memory-in-ios-memory-is-never-released-potential-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!