Question

The following method takes a double pointer to NSString and populates this with a value, as follows:

@implementation Exp
- (int) func:(NSString**) dpStr
{
    //------
    *dpStr = [self func_2];
    //------
}

Now it is being called like this:

int main ()
{
   NSString * str = [[NSString alloc] init];
   int retCode = [Exp func:&str];
   // <----- Now here I'm able to access value returned by func ------->

   [str release];    //  <--- It is crashing here 
}

Can anyone explain why it is crashing?

Was it helpful?

Solution

This allocates an empty string:

NSString * str = [[NSString alloc] init];

This replaces the previous value of str with a new string which is apparently already autoreleased; the old value of str is leaked:

int retCode = [Exp func:&str];

This attempts to release the new value of str, which is already balanced, so it's an overrelease and a crash happens:

[str release];

Neither the leading +alloc/-init nor the trailing -release are needed in this case, as the object is provided by -func:. All you need is:

NSString *str = nil;
[Exp func:&str];
// use str normally

Better would be to modify -func: to return the string directly:

NSString *str = [Exp func];
// use str normally

Then there is no need to pass it by address.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top