Creating a dangling pointer using Java

前端 未结 5 978
既然无缘
既然无缘 2021-01-06 05:57

How can i create a dangling pointer using Java?

5条回答
  •  無奈伤痛
    2021-01-06 06:33

    According to Wikipedias definition below, no.

    Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

    Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory

    There is no way to delete (or "garbage collect" if you so wish) an object which some reference still points to(1).

    Further down in the above Wikipedia article you can indeed read:

    In languages like Java, dangling pointers cannot occur because there is no mechanism to explicitly deallocate memory. Rather, the garbage collector may deallocate memory, but only when the object is no longer reachable from any references.

    The only way to make a reference not point to an ("valid") object, is to assign null to it.

    (1) Unless it is for instance a WeakReference, but then the reference is invalidated upon garbage collection.

提交回复
热议问题