views:

1123

answers:

3

Coming from a .NET background I'm use to reusing string variables for storage, so is the code below likely to cause a memory leak? The code is targeting the iphone/itouch so no automatic GC.

-(NSString*) stringExample
{
    NSString *result = @"example";
    result = [result stringByAppendingString:@" test"]; // where does "example" go?

    return result;
}

What confuses me is NSStrings are immutable, but you can reuse an 'immutable' variable with no problem.

+8  A: 

It definitely can result in memory leaks. You have to be careful about reusing in that you have to know a lot about the actual implementation of the underlying NSString object to decide if you're "safe" or not. So, if you're not using garbage collection, to be safe, you should not reuse variables the way you have.

For example, this is totally safe:

NSString *result = @"example";
result = [result stringByAppendingString:@" test"];

because the initial string was actually an objective-c string constant. This, however, would result in a memory leak:

NSString *result = [[NSString alloc] initWithUTF8String:argv[0]];
result = [result stringByAppendingString:@" something more"];

This, however, would be safe since you never owned result in the first place:

NSString *result = [NSString stringWithUTF8String:argv[0]];
result = [result stringByAppendingString:@" something more"];

So basically, if you don't own the object or you have garbage collection turned on, it is safe. If, however, you own the original object and you do this, you will be leaking memory.

Jason Coco
+2  A: 

Chiming in on Jason's answer: If you don't call retain, init, copy, mutableCopy or use one of the initWithSomething methods, you don't own the object.

So in your code, @"example" is a string constant stored in the compiled code so there is nothing to release. And, since you are returning a stringWithString you don't own the object and can assume that it will be autoreleased at some point in the future.

Abizern
A: 

"It definitely can result in memory leaks. You have to be careful about reusing in that you have to know a lot about the actual implementation of the underlying NSString object to decide if you're "safe" or not. So, if you're not using garbage collection, to be safe, you should not reuse variables the way you have."

But the .Net guy never used illegal statements that will cause memory leaks! The statements above are definitely legal and will return the string @"example test".

aimacworx