Dangling pointers in objective c - does nil also r

2019-02-16 21:44发布

问题:

What I understand is:

Memory leaks occur when memory has not been freed or "released" Dangling pointers occur when the pointer is NOT set to nil AND the object is released.

my question is: Can setting the object to nil free the memory and clear the pointer reference?

i.e.

Car *myCar = [[Car alloc] initWithCoolRims: YES];
myCar = nil;
//no mem leaks or dang pointers

or does the ARC do this:

Car *myCar = [[Car alloc] initWithCoolRims: YES];
[myCar release];    
myCar = nil;
//no mem leaks or dang pointers

Thankyou

回答1:

Under ARC

For your first example myCar will be set to nil and the newly created Car will get deallocated at some point. This is because myCar is the only thing that has a reference to your newly created Car.

If something else had a strong pointer to the newly created Car then this would simply nil out myCar's reference and the other interested references would determine the lifetime of the Car instance

Under Non-ARC

People still do this?

Your first example would indeed be a memory leak - you have lost the only pointer to your new Car instance without decrementing the +1 reference from the alloc.



回答2:

You do the first, ARC does the equivalent of the second. There are no dangling references, with or without the nil assignment, since ARC retained the referenced object (retain count 1) and when execution moves beyond the scope of the myCar definition, ARC will guarantee a release of myCar's referenced object, decrementing the reference count and deallocating the object memory if the resulting reference count is 0.