Voloda2
Voloda2

Reputation: 12607

Why do I have potentially leak in CFURLCreateStringByAddingPercentEscapes?

My code is:

NSString *buffer = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)name, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);

NSString *totalString = [NSString stringWithFormat:@"buffer/%@", buffer];

I ran "build and analize tool" and saw : " Object allocated on line 979 and stored into 'buffer' is no longer referenced after this point and has a retain count of +1 (object leaked)".

Why do I potentially have a leak in CFURLCreateStringByAddingPercentEscapes?

Upvotes: 1

Views: 1309

Answers (5)

Peter
Peter

Reputation: 288

Under ARC you should transfer memory management of the returned value using __bridge_transfer:

    NSString *buffer = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)name, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);

Upvotes: 5

Daniel
Daniel

Reputation: 22395

CFURLCreateStringByddingPercentEscapes creates a string with ref count of +1 so you need to release buffer (or autorelease) in order to not leak it..

Upvotes: 0

Felix
Felix

Reputation: 35384

This is because of the "Create Rule":

Core Foundation functions have names that indicate when you own a returned object:

  • Object-creation functions that have “Create” embedded in the name;
  • Object-duplication functions that have “Copy” embedded in the name.

If you own an object, it is your responsibility to relinquish ownership (using CFRelease) when you have finished with it.

Upvotes: 1

Elmo
Elmo

Reputation: 407

What can happen is the analyzer gives you an error on a line, in your case 979, but the object its referring to is actually above it

Without seeing your code I can't be sure but read up a few lines and might see where the error is actually coming from and XCode is only seeing the leak where it's being used

Upvotes: 0

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

If you look at this, you will see that you are allocating as the method has Create in it but not relinquishing the ownership of the string.

Release what you own and you own buffer. Add,

[buffer release];

after you get totalString.

Upvotes: 1

Related Questions