This did surprise me, I'm playing with Java Unsafe. Basically what I am testing is
Allocate unsafe memory -> free the memory -> Write to the freed memory
I was expecting to see some kind of segmentation fault error as I am accessing memory that was freed, but surprisingly, no error / exception was raised.
My code is:
protected static final Unsafe UNSAFE;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
UNSAFE = (Unsafe) field.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void test() {
long ptr = UNSAFE.allocateMemory(1000);
UNSAFE.freeMemory(ptr);
UNSAFE.putOrderedLong(null, ptr, 100L);
}
My question is, if so then why do we need the freeMemory()
function in Unsafe? What is it really for?
int*p = malloc(1000); free(p); p[0] = 1;
will "work" (by work I mean not crash) (as will the same usingnew
anddelete
.) – AggieallocateMemory
is to mark the memory as occupied, and thenfreeMemory
is to unmark them so that OS can allocate the memory to other processes. But in the event the freed memory is not reallocated to other processes, it is still accessible to everyone? – Stultzmalloc
andfree
do is to help you manage the memory to prevent memory leak.malloc
return pointer to memory address that is not allocated bymalloc
before, or allocated bymalloc
thenfree
before. If you do notfree
an address allocated bymalloc
when you no longer need that memory, that address will then be not usable in the future. If youfree
the address, and write to it,malloc
may consider that address is free and allocate it to subsequentmalloc
call, which may cause your data at that adress lost. Not sure if this is the same in java. – CatadromousMallocScribble
is particularly apropos: If set, fill memory that has been deallocated with 0x55 bytes. This increases the likelihood that a program will fail due to accessing memory that is no longer allocated. – Valerio