问题
What is the difference between garbage and dangling references?
回答1:
A dangling reference is a reference to an object that no longer exists. Garbage is an object that cannot be reached through a reference.
Dangling references do not exist in garbage collected languages because objects are only reclaimed when they are no longer accessible (only garbage is collected). In some languages or framework, you can use "weak references", which can be left dangling since they are not considered during collection passes.
In languages with manual memory management, like C or C++, you can encounter dangling pointers, by doing this for instance:
int * p = new int;
delete p;
int i = *p; // error, p has been deleted!
回答2:
A dangling reference is a reference to an object that doesn't exist anymore.
What is considered garbage depends on the implementation of your garbage collector.
With both tracing and reference counting GCs, dangling references cannot exist (unless there's a GC implementation bug) because only those elements are considered eligible for garbage collection to which no reference exists.
Thus, dangling references are an issue pretty much only for systems with manual memory management.
回答3:
Dangling Reference: Reference to a memory address that was originally allocated, but is now deallocated
int x= 1000; //creates a new
memory block
int* p = x; // *p is the pointer to address block 1000(mem location)
int *p = 20;
printf("%d",*p); //This pointer prints 20
delete p;
printf("%d",*p); // This would throw an error, because now p is
// inaccessible or dangling. *p is a dangling pointer.
Garbage: Memory that has been allocated on the heap and has not been explicitly deallocated, yet is not accessible by the program. Java has a garbage collector. It timely removes dangling pointers and other garbage memory.
来源:https://stackoverflow.com/questions/5900165/what-is-the-difference-between-garbage-and-dangling-references