Reputation: 2791
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
Upvotes: 5
Views: 5376
Reputation: 132979
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.
Upvotes: 0
Reputation: 726599
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;
Upvotes: 8