简体   繁体   中英

potential memory leak encode url

Why am I getting memory leaking while analyzing using XCode?

NSString *email = [defaults objectForKey:@"email"];
NSString *encodeEmail = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));


NSString *urlp1=@"/xyz/xx/";
NSString *fullUrl=[urlp1 stringByAppendingString: [NSString stringWithFormat:@"%@/following", encodeEmail]];

From transitioning to ARC release notes

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.

It means encodeEmail doesn't have the ownership of the allocated memory, and so it won't be released by ARC.

I think you should use __bridge_transfer

__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible for relinquishing ownership of the object.

NSString *encodeEmail = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

You are using CFURLCreateStringByAddingPercentEscapes which you have to release since you own it(Check the 'create' in the name)

You can try it as,

CFStringRef stringRef = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
encodeEmail = [NSString stringWithFormat:@"%@",(NSString *)stringRef];
CFRelease(stringRef);

Update: If you are using ARC, you can also use __bridge_transfer for transferring ownership from created CFObjects to NSObjects . You just have to use it as NSString *encodeEmail = (__bridge_transfer NSString *)...

Because you will leak an object. To be specific the the CFString returned by the method CFURLCreateStringByAddingPercentEscapes that method, which includes the keyword "create", returns a retained item. You must either manually release it, or tell ARC to handle it for you using:

NSString *encodeEmail = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)email, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

Note the __bridge_transfer that lets ARC handle the memory management for you, and it will eliminate your warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM