In article
<795a7c3f-fcbb-4704-b9fe-a076a2ce8fc0 RemoveThis @k39g2000hsf.googlegroups.com>,
sebastien.wailliez RemoveThis @gmail.com wrote:
> Hello,
>
> I have a big memory leak in a method which simply reads from a text
> file and adds each line to an NSMutableArray as an NSString, and then
> return the array to the caller.
>
> I'm positive that the memory used by the array of strings is not freed
> unless Activity Monitor and ObjectAlloc both lie. ObjectAlloc does not
> show any decrease in the number of allocated (and living!) CFStrings,
> whatever I try to get the memory freed.
>
> I'm new to Obj-C and from what I read in the Apple documentation,
> arrays retain added objects and release removed objects. So I would
> expect all lines to be released when the array gets out of scope.
> Which it should do in the calling function, as I used autorelease on
> the array.
You've misunderstood a few things:
An object is only deallocated when its retain count goes down to zero.
Sending a release message to an object decrements its retain count, but
you don't know (and shouldn't care) what the retain count actually *is*
at that point. All your job is is to make sure that every object you
allocate, copy or retain eventually gets a release message.
When you send autorelease to an object, the object gets registered to
receive a release message at some point in the future. There's no
promise made regarding *when* but it doesn't happen when the variable
goes out of scope and you really wouldn't want it to else you'd never be
able to reliably return an object as a function result. As an
implementation detail in extant releases of the framework, it will
happen at the end of the current pass through the event loop unless
you've introduced your own autorelease pool in the course of your
processing.
> I tried without autorelease and an explicit release message
> in the calling function, I tried removeAllObjects... Nothing works.
> Any clue?
Most likely the strings are still being retained by something at the
point where you're taking your measurements.
The short answer is: There's no leak in the code you posted as far as I
can see.
>> Stay informed about: Basic memory management question