How to free memory in iOS: memory is never released; potential memory leak indicated by

I have the following code designed to convert an NSMutableString to an 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 parse 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 free the object by doing "free (bytes)" then I get my function useless ... any help I would appreciate

+3
source share
1 answer

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

To resolve this issue, replace

 return [NSData dataWithBytes:bytes length:c]; 

from

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

Source: https://habr.com/ru/post/1495596/


All Articles