Question:
What happens to dangling pointers in Java? Supposedly there is garbage collection, but when is it performed? From what I
have read, it seems really easy to have persistent dangling
pointers (pointers to objects that no one is using that aren't being cleaned up by garbage collection).
Let's say I have a collection of objects, and one of the functions that manipulates the collection is called removeObject(int i)
, which removes the ith object from the collection and returns a pointer to the removed object.
Sometimes I need to get the removed object to salvage it for reuse; other times I simply want to remove the object. Is the returned pointer left dangling if I don't assign it when I make the function call? Should it be left to the function-caller to dispose of unused objects, or should the programmer make
two functions, deleteObject()
and removeObject()
?
Answer:
By definition, a dangling reference is an active binding between a
name and a de-allocated segment of the heap. By definition, garbage
is a segment of the heap that is no longer bound to a name by an
active binding. Only garbage is de-allocated by the garbage collector;
hence, a dangling reference is not possible. This, and no memory
leaks, are the principle advantages of garbage collection.
If I understand your example, you are asking what the difference is
between
removeObject(i);
and
x = removeObject(i);
Assuming there are no other active references to the i-th object
of the collection, this object becomes garbage after the first
call. A pointer to the object was returned, but was not bound to
a name, hence there is no dangling reference.
By contrast, the returned pointer was bound to x in the second call, so it
can still be accessed through the name x, and is not garbage.