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

ios, memory-leaks, memory-management, xcode

Solution

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;

Problem

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

Original source