Creating a dangling pointer using Java

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

How can i create a dangling pointer using Java?

5条回答
  •  梦毁少年i
    2021-01-06 06:26

    It depends on your definition of dangling pointer.

    If you take the Wikipedia definition of a dangling pointer, then no, you can't have it in Java. Because the language is garbage collected, the reference will always point to a valid object, unless you explicitly assign 'null' to the reference.

    However, you could consider a more semantic version of dangling pointer. 'Semantic dangling reference' if you will. Using this definition, you have a reference to a physically valid object, but semantically the object is no longer valid.

    String source = "my string";
    String copy = source;
    
    if (true == true) {
        // Invalidate the data, because why not
        source = null;
        // We forgot to set 'copy' to null!
    }
    
    // Only print data if it hasn't been invalidated
    if (copy) {
        System.out.println("Result: " + copy)
    }
    

    In this example, 'copy' is a physically valid object reference, yet semantically it is a dangling reference, since we wanted to set it to null, but forgot. The result is that code that uses 'copy' variable will execute with no problems, even though we meant to invalidate it.

提交回复
热议问题