ObjC deallocation

Status
Not open for further replies.
Seems I've been leaking memory left, right and center. Here's a program that isn't doing what I thought it should. Namely, it takes too long to crash. (When was the last time you said that?)

Code:
	NSObject* a = [NSObject new];
	NSLog(@"%d", [a retainCount]);
	[a retain];
	NSLog(@"%d", [a retainCount]);
	[a release];
	NSLog(@"%d", [a retainCount]);
	[a release];
	NSLog(@"%d", [a retainCount]);
	[a release];
	NSLog(@"%d", [a retainCount]);

Expected output: 1, 2, 1, crash
Real output: 1, 2, 1, 1, crash
 

russ-iha

Ars Praefectus
4,407
Subscriptor
Just because an object is deallocated doesn't mean the memory is zeroed out (or the pointer nil'd for that matter). When the retain count is zero, its memory is put back in the free list and as far as the Objective-C contract goes you are entirely at your own risk if you attempt to use that pointer to do anything, including asking for retainCount. IIRC, the runtime doesn't actually bother to set the retain count to zero, it just skips right to dealloc then free() (why bother setting something to zero when it is a violation to attempt to access the object ever again? by definition you shouldn't be asking for a retainCount - or anything else). This might even vary on different devices.


Personally, if I am not using a retain property and manually managing a pointer I will always nil it out when I expect it has been released for the last time; it helps in debugging later because you don't end up interacting with a zombie object for a while, leading to a crash later in a weird spot.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Tiiba,

You are taking a very error prone approach to objective-c. It will NOT payoff in your favor.

Do you know what happens when an object is released? Fuck all. The object still exists, but is not valid. References to it may work, or they may not. It depends on whether the program has re-utilized the memory or not. Something which would require significant knowledge of the memory allocation routines used to have even the vaguest of ideas on.

Read the objective-c documentation; don't try and use a "New world explorer" approach, you won't learn anything good, and you will become reliant on a perception of how it works rather than the reality of it.


Allocation rules:
If you allocate it you own it. You must release it.
If you need it for a time and you don't already own it you should retain it and release it when you are done.
If it is returned by a method other than new, alloc or init then you don't own it unless you retain it.
 
brianfcoleman":2y3up6y8 said:
Hi,

new implies you take ownership of the object.
Then you retain it.
Therefore you need to release it twice before it is deallocated.
That's why there is no crash until after you call release a third time.
Also, you can't rely on the output of retainCount to tell you anything useful.

So the object should disappear after the second release, which is why it disappears after the third release?

I'm definitely missing something.
 

Catfish

Ars Tribunus Angusticlavius
9,954
In this particular (contrived) case, where you have an object from [NSObject new], which is retained for you, then you retain again, yes, you'd need 2 releases to balance that.
If you want to convince yourself of this, turn on NSZombieEnabled (http://www.cocoadev.com/index.pl?NSZombieEnabled).

Finally, read http://developer.apple.com/library/mac/ ... yMgmt.html.
 

JamesW

Ars Tribunus Militum
1,946
Subscriptor
Things being undead after being disposed of isn't unique to ObjC. Does this compile error free? What's the output?

free.c
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
  char* msg = calloc(20, sizeof(char));
  strcpy(msg, "Hello World!");
  puts(msg);

  free(msg);

  puts(msg);
}

---

gcc -std=c99 -o free free.c

How about this?
free.c
Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
  char* msg = calloc(20, sizeof(char));
  strcpy(msg, "Hello World!");
  puts(msg);

  free(msg);

  char* notMsg = calloc(20, sizeof(char));
  strcpy(notMsg, "This isn't msg!");

  puts(msg);
  free(notMsg);
}

---

gcc -std=c99 -o free free.c

Technically they're as undefined as ObjC code that over-releases. Still, I'm pretty confident about the real world output.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Tiiba":1ivtzpox said:
So two IS enough? That's all I want to know.

You need to be sure and understand why.

The example you posted is (obviously) very contrived; but leads me to believe you are taking a trial and error approach to using Objective-C. Your other questions and postings related to Objective-C are similar. The underlying core of Objective-C is C. Objective-C is not a language designed similarly to C, it is C with an object framework embedded in it. As such Objective-C suffers from the many failings of C in comparison to the vast majority of C-like, or C-derived languages that have followed it. Java, and C# share many syntactical similarities to C but their core is so substantially different they do not suffer from the level of ambiguity that C presents to new developers. Syntax similarities are the only thing they really have in common. (And that has been diverging anyway).

C is a beautiful but unforgiving mistress. If you treat her right she will dance a beautiful endless ballet, treat her wrong and she will whisper hateful things into your ear and wait until the opportunity is right and will rip out your heart to crush it lifeless on the floor.

--

I had written a large response to your Table View thread, but I didn't post it, I had difficulties getting my point across, after reading this thread I feel the need to post in regards to the other thread as well. You need to accept that some things in Objective-C and Apples API frameworks are in the category of "This is how things are done and are not to be questioned". It sucks, but it's true.

Apple has determined that UIView allocations are expensive and creating a pool of UITableViewCell objects and recycling the pool is the way to use a tableView. You can fight it, but you cannot win. I will say that I despise that particular design choice as it gives me fits when I want a simple TableView with a few specialized cells in them. I found an example on the net where someone had created 1 subclass per Section for a TableView and I've found that it allows me to have code which is simple and straightforward enough that complex TableView settings screens don't give me hives.

The basic premise is simple enough: Your UITableView delegate has an array of Sections, each section is an instance of a class similar to the UITableView delegate. In your TableView delegate you call the section specific method in the section instance. This means if you have 4 sections in a UITableView that you have 4 classes to handle the various cells. If you use a new section for different cell types it can help simplify some of the special handling. A project I worked on recently has 1-3 cell types per section, with 4-5 sections per tableview. That would be up to 15 special cell types in a single UITableView delegate if it weren't broken down. Instead, with only a couple of cell types per section (and many with only a single cell type) it becomes much easier to handle both mentally, and code wise as the logic is straightforward and short.
 

russ-iha

Ars Praefectus
4,407
Subscriptor
Tiiba":2f1meckz said:
So the object should disappear after the second release, which is why it disappears after the third release?

I'm definitely missing something.


Re-read my post again, it explains this quite clearly... you are trying to reason about a situation that Objective-C has told you produces undefined behavior. When you do a release on the object and retainCount hits zero, the runtime doesn't bother setting the retainCount to zero because you told it that you were done with the object and therefore by definition that memory no longer matters because you just promised not to access it again. The fact that you were able to check the value of retainCount again after that is purely an accident... you might very well have gotten EXEC_BAD_ACCESS... or the value 9284723.

JamesW pointed out the same thing... if you allocate a buffer, write some crap to it, free() it, then try to access it again what happens? The answer is anything can happen because that behavior is undefined. The memory might still be there untouched... it might have been overwritten by another program... those pages may not be mapped anymore so accessing them might generate a fault that kills the program. Who knows? That's the awesome part of ref counting/free() bugs. Their behavior is undefined and so generates random/nonsensical results and/or crashes.
 
Status
Not open for further replies.