Question

Should a CFRelease be always followed by assignment to NULL? Consider the following code

personRef is an ABRecordRef, from which I am trying to extract the address label.

ABMultiValueRef addrRef = ABRecordCopyValue(personRef, kABPersonAddressProperty);
CFStringRef lbl = ABMultiValueCopyLabelAtIndex(addrRef, i);
if(lbl!=NULL) {
    //fetch the label and store it in NSString here.
    //...
    CFRelease(lbl);
    lbl=NULL; //Is it a better practice or mandatory to assign lbl to NULL?
}

I could still see some address value in the debug window, which is why I'm asking :-)

Was it helpful?

Solution 2

It makes no difference unless you perform further tests on the variable later in the code (i.e. the variable can be NULL sometimes, which is legal within your code).

OTHER TIPS

Setting to NULL will make it slightly more reliable that the next function you pass that value to will barf on it.

If you don't, the value may be “valid enough” and still seem to work, or work oddly, for some amount of time past the release. Eventually it will blow up and it's much harder to debug it then.

If you can guarantee that the variable will always be set to a fresh, live object after you release the previous object and before you try to use the variable again, then you can skip the NULL assignment and the analyzer may even complain about it (it'll call the NULL assignment a “dead store”).

But whenever the variable may not get reset between the release and the next usage, then you should set it to NULL immediately after the release. The analyzer can catch some problems, but not all. Setting the variable to NULL makes your program more likely to crash in a way you can recognize and debug, and makes it more likely to crash closer to the actual source of the problem (the premature release or missed point where you needed to create or obtain a new object).

When in doubt, set it to NULL. Take it out only if the analyzer complains, and even then, there will be cases when for aesthetic or consistency reasons, you may prefer to leave it in and put up with the analyzer's objection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top