Dangling pointers in objective c - does nil also release memory?

爷,独闯天下 提交于 2019-12-30 08:25:13

问题


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.



来源:https://stackoverflow.com/questions/20873253/dangling-pointers-in-objective-c-does-nil-also-release-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!