Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leak in Instruments, Reference Count and Autorelease

Instruments is reporting me a leak of a NSDate variable. But If I add up the retains and releases it should be able to release I think, by the autorelease pool. Probably I'm counting wrong but I wan't to make sure. Take a look at the RefCt. If I [Class alloc] it should come up with a retain count of 1, then if I autorelease that object, it should be able to free, or is it not?

enter image description here

like image 424
the Reverend Avatar asked Nov 18 '11 23:11

the Reverend


1 Answers

Instruments adds up the retains and releases for you. That's what the “RefCt” column shows you: The running total.

If I [Class alloc] it should come up with a retain count of 1, …

And indeed it does; that's the first row in the list.

… then if I autorelease that object, it should be able to free, or is it not?

Autorelease isn't an immediate -1; it causes a release later, and that's the -1.

So you have:

  1. Allocation: +1 (=1)
  2. Autorelease: 0 for now; causes a Release later (no change now, so still =1)
  3. Retain: +1 (=2)
  4. Release: -1 (=1)
  5. Retain: +1 (=2)
  6. Retain: +1 (=3)
  7. Release: -1 (=2)
  8. Release: -1 (=1)

Note that one of the three Releases is the one caused by the Autorelease. Only then is -1 incurred.

The object needs another release in order to be deallocated. Until that happens, it won't.

And yes, it is possible for an object that has enough outstanding autoreleases to kill it when they come due to be retained before that happens and thereby be kept alive. I saw this happen once with an object that I was under-retaining, but that was the value of a property being used by a Binding; the Binding retained the value and so kept it alive even after I had autoreleased my own last ownership of it.

like image 143
Peter Hosey Avatar answered Nov 15 '22 10:11

Peter Hosey