Reusing an NSString variable - is it causing a memory leak?
Coming from a .NET background, I am reusing string variables for storage, so the code below might cause a memory leak? The code targets iphone / itouch so there is no automatic GC.
-(NSString*) stringExample
{
NSString *result = @"example";
result = [result stringByAppendingString:@" test"]; // where does "example" go?
return result;
}
What confuses me is that NSStrings are immutable, but you can use an "immutable" variable without any problem.
a source to share
This can definitely lead to memory leaks. You have to be careful when reusing it, as you need to know a lot about the actual implementation of the main NSString object in order to decide if you are "safe" or not. So, unless you are using garbage collection, to be on the safe side, you shouldn't reuse variables the way they are.
For example, this is completely safe:
NSString *result = @"example";
result = [result stringByAppendingString:@" test"];
because the original string was actually an objective-c string constant. This, however, will result in a memory leak:
NSString *result = [[NSString alloc] initWithUTF8String:argv[0]];
result = [result stringByAppendingString:@" something more"];
This, however, would be safe as you never owned the 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 enabled, it's safe. If, however, you have the original object and you do, you will be leaking memory.
a source to share
Enabling Jason Answer: If you do not call retain
, init
, copy
, mutableCopy
or use one of the methods initWithSomething
you are not the owner of the object.
So, your code @"example"
has a string constant stored in the compiled code, so nothing to release anything. And, since you are returning stringWithString
, you are not the owner of the object and can assume that it will auto-implement at some point in the future.
a source to share
"This can definitely lead to memory leaks. You have to be careful with reuse in that you need to know a lot about the actual implementation of the underlying NSString object in order to decide if you are safe or not. So, if you are not using garbage collection to be safe, you shouldn't reuse variables the way you do. "
But the .Net guy never used illegal statements that could cause memory leaks! The above statements are definitely legal and will return the @ "example test" line.
a source to share