PowerAktar
PowerAktar

Reputation: 2428

Memory leak for variables created inside methods

To me, the following code looks like it will create a leak -- I might be wrong about this though:

-(NSString*) myString{

   NSString* foo  = @"bar";
   return foo;

}

My question is:

1) Will is create a memory leak as foo is not released?

2) If it IS a memory leak then how do I avoid it?

Upvotes: 2

Views: 97

Answers (2)

bealex
bealex

Reputation: 10014

Short answer. This code will not give a leak.

Long answer:

With NSString it is not always visible leak, because of strings intern and because you do not call alloc/new/copy methods. But yes, this is a classic point of memory leak in general.

There are two ways of dealing with it.

  • tracing all objects that you are returning from this (or similar) method and releasing them. That's extremely buggy possibility and a very bad one almost every time.
  • returning autoreleased instance. In fact, you did something like it implicitly here. This string assignment is similar to:
NSString *foo = [NSString stringWithString:@"bar"];

And this one is similar to:

NSString *foo = [[[NSString alloc] initWithString:@"bar"] autorelease];

So, you will return an object, that has retain count 1, but is autoreleased. So, when NSAutoreleasePool will be drained, this object will go away.

Upvotes: 3

Felix
Felix

Reputation: 35384

It is not a leak. @"bar" is a statically allocated string and thus foo doesn't need to be retained. You can handle these strings like autoreleased objects although they will resist in memory for the runtime of the application.

You can turn it into a leak by returning [foo retain] or [foo copy].

Technically it makes no sense to retain static variables. But if you copy them, you have to release them.

Upvotes: 4

Related Questions