How can i create a dangling pointer using Java?
You can not create dangling pointer in java, because there is no mechanism to explicitly deallocate memory
String foo = null;
then if you try to say foo.substring(0)
, you'll get a NullPointerException.
Is that what you mean?
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.
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.
Not available on all JVMs, but Sun's JVM does give you sun.misc.unsafe#allocateMemory(long bytes)
. That call returns a pointer.
sun.misc.unsafe#freeMemory(long address
) frees that memory. Your initial pointer is now "dangling".