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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With