Search code examples
javacrashbufferlwjgl

Java crash when freeing intbuffer


Whenever I run the following code java returns an EXCEPTION_ACCESS_VIOLATION when freeing the IntBuffer:

public int[] size(){
    IntBuffer size=BufferUtils.createIntBuffer(2);
    long address=MemoryUtil.memAddress(size);

    GLFW.nglfwGetWindowSize(this.handle, address, address+Integer.BYTES);
    int[] result=new int[]{size.get(0), size.get(1)};

    JEmalloc.nje_free(address);

    return result;
}

Pastebin


Solution

  • The ByteBuffer created by BufferUtils will be released by the garbage collector when there's no more references to it.

    If you want to use JEmalloc.nje_free() to free the buffer, then you also need to use JEmalloc when allocating the buffer.

    IntBuffer size = JEmalloc.je_malloc(2 * Integer.BYTES).asIntBuffer();
    long address = MemoryUtil.memAddress(size);
    
    [...]
    
    JEmalloc.nje_free(address);