Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 259
Cescy Avatar asked Jan 01 '14 21:01

Cescy


People also ask

Does dangling pointer cause memory leak?

Solution of this problem: Make the variable x is as static variable. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer. In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations.

What happens when we access dangling pointer?

Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.

What is the difference between a dangling pointer and a memory leak?

Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. In opposite to the dangling pointer, a memory leak occurs when you forget to deallocate the allocated memory.

What is a dangling pointer What problems can it cause?

The pointer is considered to be "dangling" since it points to memory that may no longer hold a valid object. Because the memory may contain completely different data, unpredictable behavior can result when a programmer mistakenly dereferences the pointer to access the object.


1 Answers

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.

like image 58
Paul.s Avatar answered Oct 05 '22 14:10

Paul.s