Create a dangling pointer using Java

How to create a dangling pointer using Java?

+4
source share
5 answers

According to Wikipedia's definition below, no .

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

Dangling pointers occur when an object is deleted or freed without changing the value of the pointer , so that the pointer still points to the memory location of the freed memory

It is impossible to delete (or "garbage collection" if you wish) an object that some link still points to (1) .

Further in the above Wikipedia article you can really read:

In languages ​​like Java, dangling pointers cannot occur because there is no mechanism for explicitly freeing memory. Rather, the garbage collector can free up memory, but only when the object is no longer accessible from any links.

The only way to make a link not a reference to an object ("valid") is to set it to zero.

(1) If this does not mean, for example, WeakReference, but then the link is canceled upon garbage collection.

+14
source

You cannot create a dangling pointer in java because there is no mechanism for explicitly freeing memory

+3
source
String foo = null; 

then if you try to say foo.substring(0) , you will get a NullPointerException .

Is that what you mean?

+1
source

Not available for all JVMs, but the Sun JVM gives you sun.misc.unsafe#allocateMemory(long bytes) . This call returns a pointer.

sun.misc.unsafe#freeMemory(long address ) frees this memory. Your start pointer now hangs.

0
source

It depends on your definition of the dangling pointer.

If you take the Wikipedia definition for a dangling pointer, then no, you cannot have it in Java. Since the language is garbage collection, a link always points to a valid object, unless you explicitly assign the link "null" to the link.

However, you might consider a more semantic version of a dangling pointer. "Semantic chatty link" if you want. Using this definition, you are referring 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, but semantically it is a chatty reference, since we wanted to set it to null, but forgot. As a result, code using the "copy" variable will execute without problems, even if we want to make it invalid.

0
source

Source: https://habr.com/ru/post/1339450/


All Articles