It seems that in Objective-C, the method that is responsibile for memory allocation (like malloc()
in C), is -[NSObject alloc]
. What about freeing that memory? Is that done by -[NSObject dealloc]
? Is that why in our own class's dealloc
, we must call [super dealloc]
last, instead of first?
I ask because I don't understand why, if I put [super dealloc]
first, and release an object using [_bar release]
on the next line, I don't get a segmentation fault. After [super dealloc]
runs, if it frees the object's memory, _bar
should already be a memory chunk that doesn't belong to the process.
I think you are saying, you have this code:
- (void)dealloc
{
[super dealloc];
[_bar release]; // _bar is a member variable
}
And you expect to get a segmentation fault on the second line, but in practice you are not.
The reason for this is luck!
The OS will trap access to memory that your process does not own, but it doesn't police everything that happens inside your process. In this case, you are accessing memory that you have marked as free, but it still belongs to your process, and so behavior is undefined. The memory was valid a few milliseconds ago, and so it is likely that nobody has started reusing this page of memory yet, and so it probably still has valid data on it. So it might succeed. But it also might fail.
This is bad code and you shouldn't ship it. But just because it is incorrect and undefined doesn't mean it won't work.