Set pointers to nil after release? - objective-c

After releasing objects is it best to set the pointers to nil? Thats what I have been doing, just wanted to ask if its necessary, good practice or overkill?
- (void)dealloc{
[planetName release]; // NSString instance variable
[super dealloc];
}
#end
.
- (void)dealloc{
[planetName release]; // NSString instance variable
planetName = nil;
[super dealloc];
}
#end
cheers -gary-

Depends on the scope of the variable that holds the pointer. I always set pointers to nil if they continue to exist within the scope, just in case I'm calling the variable again somewhere else. Otherwise, there's a risk that I would access a memory location that contained an object which is now released.
But if the variable goes out of scope, then it won't be used either, thus assigning nil to it is a bit overkill. Still, it is a good practice to just assign nil just in case someone else decides to add code to your code and accidently uses the variable again within it's scope but after it was freed.

Usually when programming in C/C++ I set it to null. Why? Because even if you free the memory being pointed, the pointer still holds the address of that freed memory. It can cause a serious access violation problems in code like this:
if(myPointer != null)
{
doSomething(myPointer);
}
If you had set your pointer to null, this will never happen

It's considered good practice. If you set your pointers to nil after releasing them, then in case you misuse your variable at a later point of execution, you'll get a proper error.

At times this can be crucial, as I just found out. I use a camera in my game which keeps a pointer to a generic target. If you return to the main menu from a level then it clears the level from memory but keeps the camera and game layers.
-(void) dealloc {
[target release];
target = nil;
[super dealloc];
}
Since the camera will exist longer than the target, it's best to set target to nil, otherwise when the level loads again and you set a new target:
-(void) setTarget:(CCNode *)aTarget {
[target release];
target = [aTarget retain];
[self update:0];
}
It will crash on that release if the target is junk and not nil. Sending a message to nil is fine, but not to some arbitrary junk memory. That gives me a EXC_BAD_ACCESS.

Related

Basic memory management confusion

I bet that I could find the answer of this question from reading similar threads here or by googling, but I would like "hear" it first hand so to speak because it's an anomaly in my understanding.
So here's the thing, I have some code which a previous employee wrote and I see a lot of a certain type of construct which looks rather odd to me and I just want to clarify what is "right and wrong".
For example
- (void) setWwanServiceId: (NSString *) newValue {
[wwanServiceId autorelease];
wwanServiceId = [newValue copy];
}
Here wwanServiceIdis a NSString member of the class, and to me this seem like a strange way to do it. As far as I understand it would begin by putting an autorelease on the object, basically saying: "whenever this object seem to not be used, release it for me I don't really care" then the copy will up the retain count +1 on.... wwanServiceId? or newValue? I guess the first.
Then to make me all more confused let's just quickly run through the life-cycle of the wwanServiceId-string..
basically the value will be set if we receive a notification which then from the notification-handler method will call the above -setWwanServiceId: method. other than that it will only ever be accessed for reading, so we are safe to say that it will at any given point:
put autorelease on object
retain a new string copy
Then there is one more quirk to this and this is where I am getting rather suspicious, namely in the -dealloc method which looks like this:
- (void) dealloc {
[[self wwanServiceId] release];
[super dealloc];
}
So what happens there? it will afaik release the wwanServiceId and as I said the only time it's memory management is being touched (if I haven't missed anything but I feel pretty sure) is to put an autorelease and retain it.
So to summarize:
Is the idea here that he thought that since he always retain a new copy after putting autorelease he need to release it in the end.. or well it's the only thing I can think about. Or just felt it would be safe to do an extra release in the end just in case..?
Because as far as I understand it, if this setter is called one time it will put an autorelease (-1 in future), do a retain (+1) and when destructor is called it will do the "final release" (-1).
Any ideas or suggestions helping me understand (if in fact I am wrong and the memory handling is correct as is) would be appreciated.
You wrote:
Here wwanServiceIdis a NSString member of the class, and to me this seem like a strange way to do it. As far as I understand it would begin by putting an autorelease on the object, basically saying: "whenever this object seem to not be used, release it for me I don't really care" then the copy will up the retain count +1 on.... wwanServiceId? or newValue? I guess the first.
This seems to point to the source of your confusion. wwanServiceId is a variable which can contain a reference to an object of type NSString. Variables do not have reference counts only objects do.
The previous employee wrote:
- (void) setWwanServiceId: (NSString *) newValue {
[wwanServiceId autorelease];
wwanServiceId = [newValue copy];
}
The expression [wwanServiceId autorelease] means: read the reference stored in wwanServiceId and autorelease the object that reference refers to - let's call that object A. Important: This does not delete object A; it will be released as some later stage and if at that time there are no remaining references object A will be deleted.
The expression [newValue copy] means: read the reference stored in newValue, use that to locate the object (call it object B), make a copy of that object to produce a new object (call it object C), and return a reference to the new object. This new object is owned by the caller of copy, so there is no need to retain it.
Finally the assignment stores the reference to object C into wwanServiceId.
So there is a maximum of three distinct objects involved:
A: the original object referenced by wwanServiceId, this is autoreleased to remove the ownership of wwanServiceId.
B: the object referenced by newValue, this is left untouched
C: a newly created copy of B owned through wwanServiceId
Why "autorelease" in the code and "maximum of three distinct" above?
The method could be called with newValue referencing object A, e.g. as in:
[self setWwanServiceId:[self wwanServiceId]]
If this was to occur and (a) release was used instead of autorelease and (b) there was no other reference to object A then the release would delete object A and then when [newValue copy] was evaluated newValue would be referencing a deleted object... The use of autorelease in this case delays the deletion until after the copy.
So what the previous employee wrote is not in any way "wrong", but as some of the other answer suggest it may be an unusual style. Another way you see this written is:
- (void) setWwanServiceId: (NSString *) newValue
{
NSString *oldValue = wwanServiceId;
wwanServiceId = [newValue copy];
[oldValue release];
}
which also ensures any deletion occurs after the copy.
HTH.
To be short and helpful:
This is wrong:
- (void) setWwanServiceId: (NSString *) newValue {
[wwanServiceId autorelease];
wwanServiceId = [newValue copy];
}
This is right:
- (void) setWwanServiceId: (NSString *) newValue {
if (newValue != wwanServiceId) {
[wwanServiceId release];
wwanServiceId = [newValue copy];
}
}
To explain in short:
[wwanServiceId autorelease]; is an unnecessary sent message, because autoreleasing an object will reduce the retain count at some unknown point in the future. And in the next line you are wwanServiceId = [newValue copy]; instantly setting the instance variable. So, in your memory you now have a to be autoreleased object and a new object. One of them is too much The new object is, where the pointer of your IVar is pointing to. The old one is swimming in your Memory Pool with probably no reference to it :-)
Autorelease as few as possible or use ARC.
Oh: And in the dealloc method, please do not send the message like this:
[[self wwanServiceId] release];
Better like this:
[wwanServiceId release];
as Apple recommends to work directly with instance methods in init and dealloc methods, instead of using getters and setters there.
Debug it and have a look.
[wwanServiceId autorelease];
wwanServiceId has an address. This statement does not change it. It does decrement the retain count of this object though.
Thats it.
wwanServiceId = [newValue copy];
This statement creates a new object. The new object is a copy of newValue. Compare the addresses of the objects and you will see, that the address inn wwanServiceId will vary from the address of newValue and it will vary from the address that wwanServiceId did have just before the statement was executed.
The retain, that is implicit in copy will affect wwanServiceId, but it affects the new object, that was just creaed with copy. It does not affect the wwanServiceId object which was autoreleased during the statement before.
At some point after the execution of setWwanServiceId had finished, the old and autoreleased object will dissappear. (Assuming that the retain count is 0 now. If it is >0 because it is still retained for other reasons or just for error, then it will remain and potentially cause a leak.)
Once you understood that you will not question any more what is happening in the dealloc method. wwanServiceId is released. Meaning its retain count is reduced by 1. In the event that it is 0 then it will be deallocated automatically.
You could even autorelease it there too. The diffrerence to autorelease is basically that an autoreleased object is still around and available while the current method is being executed. Its release comes into effect at some later point in time.
But there is no reason for autoreleasing the object in dealloc.
In the example given there is not even a good reason to autorelease the object in the setter setWwanServiceId. You may well release the object directly in both methods.
Assuming wwanServiceId is the private ivar mapped by the getter wwanServiceId and setter setWwanServiceId, I think it is not correct to autorelease the ivar in the setter.
I would have coded the following:
- (void) setWwanServiceId: (NSString *) newValue {
if (newValue != wwanServiceId) {
[wwanServiceId release];
wwanServiceId = [newValue copy];
}
}
What I mean is: it is not necessary to give ownership of your var to the autorelease pool (which it may be drained at the end of the application). Simply release the ivar. If someone is using it, no problem, it will have a strong reference to it. Otherwise it will be deallocated.

NSMutableArray release crashes my program -- why?

I thought I understood memory management well enough until this issue happened (Mac OS X 10.6): I have a custom NSView subclass with an NSMutableArray instance variable, but when I dealloc my view and attempt to release that instance variable, sometimes BOOM, EXC_BAD_ACCESS happens. This happens when I try to close my document window without quitting the program, but for some reason, even under identical conditions, sometimes it works without issue. Can anyone help me understand what's going on here? The relevant bits of code from my NSView subclass:
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
rainbow = [[NSMutableArray alloc] initWithObjects:
// some objects go here, followed by the nil sentinel
]
return self;
}
return nil;
}
And the dealloc method:
- (void)dealloc {
[super dealloc];
NSLog(#"Release the rainbow!");
if (rainbow) {
[rainbow removeAllObjects]; // EXC_BAD_ACCESS happens here
[rainbow release];
}
}
Even though I check whether rainbow is still around, sending it a message results in that segfault. There is one spot where it gets used: it's passed as a *info argument to a CGShading callback function. Here are the relevant bits of that function (which generally works without crashing):
NSMutableArray *colorStops = (NSMutableArray *)info;
[colorStops retain];
/*
...
*/
[colorStops release];
I'm guessing that there's something here about threads, but I really don't know. Anyone have any ideas? Thank you very much! I've reread the memory management guide; any more headdesking on this and my glass tabletop shatters in my face.
Always do
[super dealloc]
at the end of your dealloc method.
In addition to Terry's point about [super dealloc], the -removeAllObjects call will message all of the objects in the array (to release them). If you have overreleased any of those objects, the pointer that the array has may now point to deallocated or otherwise invalid space.
So, you have to review your memory management of all of the objects in the array. Run your app under the Zombies instrument. Do a Build and Analyze and resolve the identified issues.

In objective c can a class essentially delete itself?

In objective c, suppose I have an object Obj stored in a NSMutableArray, and the array's pointer to it is the only strong pointer to Obj in the entire program. Now suppose I call a method on Obj and I run this method in another thread. In this method, if Obj sets the pointer for itself equal to nil will it essentially delete itself? (Because there will be no more strong pointers left) I suspect the answer is no, but why? If this does work, is it bad coding practice (I assume its not good coding, but is it actually bad?)
It is highly unlikely that an object would be in a position to cause its own release/deallocation if your code is designed properly. So yes, the situation you describe is indicative of bad coding practice, and can in fact cause the program to crash. Here is an example:
#interface Widget : NSObject
#property (retain) NSMutableArray *array;
#end
#implementation Widget
#synthesize array;
- (id)init
{
self = [super init];
if(self) {
array = [[NSMutableArray alloc] init];
[array addObject:self];
}
return self;
}
- (void)dealloc
{
NSLog(#"Deallocating!");
[array release];
[super dealloc];
}
- (void)removeSelf
{
NSLog(#"%d", [array count]);
[array removeObject:self];
NSLog(#"%d", [array count]);
}
#end
and then this code is in another class:
Widget *myWidget = [[Widget alloc] init];
[myWidget release]; // WHOOPS!
[myWidget removeSelf];
The second call to NSLog in removeSelf will cause an EXC_BAD_ACCESS due to the fact that array has been deallocated at that point and can't have methods called on it.
There are at least a couple mistakes here. The one that ultimately causes the crash is the fact that whatever class is creating and using the myWidget object releases it before it is finished using it (to call removeSelf). Without this mistake, the code would run fine. However, MyWidget shouldn't have an instance variable that creates a strong reference to itself in the first place, as this creates a retain cycle. If someone tried to release myWidget without first calling removeSelf, nothing would be deallocated and you'd probably have a memory leak.
If your back-pointer is weak (which it should be since a class should never try to own it's owner, you will end up with a retain-cycle) and you remove the strong pointer from the array the object will be removed from the heap. No strong pointers = removed from memory.
You can always test this.
If you need a class to bring to a situation where its deleted, the best practice is to first retain/autorelease it and then make the situation happen. In this case the class won't be deleted in a middle of its method, but only afterwards.
I think we can say it might be bad coding practice, depending on how you do it. There are ways you could arrange to do it safely, or probably safely.
So let's assume we have a global:
NSMutableArray *GlobalStore;
One approach is to remove yourself as your final action:
- (void) someMethod
{
...
[GlobalStore removeObject:self];
}
As this is the final action there should be no future uses of self and all should be well, probably...
Other options include scheduling the removal with a time delay of 0 - which means it will fire next time around the run loop (only works of course if you have a run loop, which in a thread you may not). This should always be safe.
You can also have an object keep a reference to itself, which produces a cycle and so will keep it alive. When its ready to die it can nil out its own reference, if there are no other references and that is a final action (or a scheduled action by another object) then the object is dead.

Incorrect decrement error, code review

This code down below works as expected, cleans things up without Zombies. The class in which this method exists, is the owner of the Nodes, which are being released, yet, upon "Analyze" the following 2 issues show up.
If possible, could you help me understand why?
- (void) dealloc {
NSLog(#"Releasing [Doubly Linked List] .. ");
Node *thisNode = [self firstNode];
Node *nextNode = [thisNode next];
while (nextNode != nil) {
// If "Next node" is not nil, it means that
// "previous node" can now be released
NSLog(#" - releasing node \"%c\"", [[nextNode previous] charData]);
[[nextNode previous] release];
nextNode = [nextNode next];
}
[[self lastNode] release];
[super dealloc];
}
Click on the icon on the left of the message, it will show the path through the code that produces the error.
You are releasing something, [nextNode previous] that you do not own. In particular you did not alloc or retain it nor obtain it from a method that begins with new or copy so you do not have ownership of it and should not release it.
It is also very uncommon to release something not in your class, [[nextNode previous] release].
Now: [[self lastNode] release];
As above you did not obtain an ownership on the object you are releasing.
If lastNode is a property with retain you are subverting the setter and when later a value is assigned to lastNode via the setter there will be an extra release on the object and probably a crash. If it is not a property again this it very non-standard to release something that is returned by a method call.
Any releases with code of this form [[self lastNode] release] is non-standard and if be avoided there will be fewer ownership (retain/release) problems.
You will save a lot of time and grief by studying the Apple memory management documentation.
The issue is that you are not doing things according to the ordinary memory management conventions of Objective C and the static analyzer is getting confused. Basically, the Objective C class which allocates an object "owns" the object and is responsible for releasing it. Here, you are not using those conventions, so the analyzer is complaining, even if what you are doing works correctly.
See Apple's documentation for more on ownership.

Dealloc method in iOS and setting objects to nil

I have a pretty basic question. In some examples I've seen, objects are just released in the dealloc method. In others, the objects are released and then set to nil. Is there a reason for this? Is setting to nil after releasing advantageous?
Three ways to dealloc
1. Just release
- (void)dealloc {
[airplane release];
[super dealloc];
}
Now the object reference points to a random position, which may be one of two things:
Most likely it is garbage, because the memory position can't be interpreted as an object.
Rarely it will be a different object, because memory have been reused to create a new object.
The effect of a further method calls through this pointer is one of these three (which one is undefined):
A crash with EXC_BAD_ACCESS because the pointer points to garbage.
A crash with undefined selector because it points to a valid object which doesn't have that method.
A successful method execution because the new object has a method by the same name.
2. Release and nil
- (void)dealloc {
[airplane release], airplane = nil;
[super dealloc];
}
Now the object reference is nil and any further method calls are ignored. This may silently cause a defined but unforeseen lateral effect in your code, but at least it doesn't crash your application.
3. Nil and release
- (void)dealloc {
id temp = airplane;
airplane = nil;
[temp release];
[super dealloc];
}
This is the same as before, but it removes that small window between release and nil where the object reference points to an invalid object.
Which one is best?
It is a matter of choice:
If you rather crash choose just release.
If you rather ignore the mistake choose nil+release or release+nil.
If you are using NSZombieEnabled=TRUE then just release, don't nil the zombie!
Macros and zombies
A easy way to defer your choice is using a macro. Instead [airplane release] you write safeRelease(x) where safeRelease is the following macro that you add to your .pch target file:
#ifdef DEBUG
#define safeRelease(x) [x release]
#else
#define safeRelease(x) [x release], x=nil
#endif
This macro doesn't respect zombies. Here is the problem: when NSZombieEnabled is TRUE the object turns into a NSZombie. If you nil its object reference, any call sent to him will be ignored.
To fix that, here is a macro from Kevin Ballard that sets the pointer to an invalid made up reference ONLY when NSZombieEnabled is FALSE. This guarantees a crash during debug time if zombies are not enabled, but leaves the zombies be otherwise.
#if DEBUG
#define safeRelease(x) do { [x release]; if (!getenv("NSZombieEnabled")) x = (id)0xDEADBEEF; } while (0)
#else
#define safeRelease(x) [x release], x = nil
#endif
References
Apple doesn't have a recommendation on which one is best. If you want to read the thoughts of the community here are some links (the comment threads are great too):
Dealloc Jeff Lamarche
Don’t Coddle Your Code Daniel Jalkut
More on dealloc Jeff Lamarche
To nil, or not to nil, that is the question Ching-Lan Huang
Defensive Coding in Objective-C Uli Kusterer
This snippet covers all the bases and is ready to cut and paste into a .pch file.
// SAFE_RELEASE
// Releases an object, then does other things based on context.
//
// The intention is to fail early during internal testing but prevent
// customers from experiencing crashes if at all possible.
//
// For more information see:
// http://stackoverflow.com/questions/6778793/dealloc-method-in-ios-and-setting-objects-to-nil
//
// Debug build:
// If zombies are enabled, the macro just calls |release|. The zombie
// mechanism will continue to be used to find messages sent to
// the deallocated object.
// Otherwise, zombies are not enabled, so the macro sets the object to a
// invalid memory address. (0xDEADBEEF.) This will intentionally
// cause a crash if the object is used, allowing the bug to be found
// and fixed immediately.
//
// Release build:
// The macro calls |release| normally. Then it sets the object to nil to
// prevent a possible crash caused by sending a message to a
// deallocated object. Messages sent to nil are always allowed.
//
#if DEBUG
#define SAFE_RELEASE(x) \
do { \
[x release]; \
if (!getenv("NSZombieEnabled")) \
x = (id)0xDEADBEEF; \
} while (0)
#else
#define SAFE_RELEASE(x) \
[x release], x = nil
#endif
The code is functionally equivalent to Jano's second version of safeRelease, but adds documentation and compliance with Google's coding standards.
If there's a dealloc call in more than one place, setting the object variable to nil makes sure it won't be deallocated more than once by mistake. Same logic if the function with the dealloc is called from more than one place, or can be called arbitrarily by external code (i. e. other classes).
In real life, this typically happens when the enclosing object is "reusable" - supports multiple rounds of content initialization/teardown. The nil-ness of object pointers then becomes a valuable component of object state - it means that the object is "empty" right now.
Sorry for the generalities.
- (void)dealloc
{
[searchPlace release];
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.searchPlace = nil;
}
Is this like what you say?