Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C NSString malloc error

I've got a method that creates a string then appends additional strings onto it:

-(NSString*)returnDetails {
    NSString *details = [[NSString alloc] init];

    details = [details stringByAppendingString:url];
    details = [details stringByAppendingString:@" : "];
    details = [details stringByAppendingString:author];

    return [details autorelease]; 
}

And I'm getting this error:

iphoneapp_1(66508,0xacd9e2c0) malloc: *** error for object 0x6b9eb80: pointer being freed was not allocated

If I change it to

NSString *details = [NSString string];

and remove the autorelease call, then it works. I would just like to understand why this works and my original method didn't?

like image 244
harrynorthover Avatar asked Jun 27 '26 10:06

harrynorthover


1 Answers

The NSString's method stringByAppendingString: returns an object that is already autoreleased. So returning [details autorelease] from your method will make that object will be released one more time than it must. Just return details instead.

You also have a memory leak in there, because you never released the string you allocated at the top of the method. Try this code :

-(NSString*)returnDetails {
    NSString *details = [NSString string];
    details = [details stringByAppendingString:url];
    details = [details stringByAppendingString:@" : "];
    details = [details stringByAppendingString:author];

    return details; 

}