Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 762
Jesús Ayala Avatar asked Mar 23 '23 21:03

Jesús Ayala


1 Answers

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;
like image 156
Sergey Kalinichenko Avatar answered Apr 24 '23 07:04

Sergey Kalinichenko