[BUG] Double free on PointerBuffer objects

Started by KGAFT, January 09, 2025, 10:26:18

Previous topic - Next topic

KGAFT

During development of my vulkan app with lwjgl, i noticed there are a lot of glibc errors like: double free detected in tcache. After continuously investigation, i found out that all PointerBuffer object allocated through allocateDirect are garbage collected automatically, with no need to free it manually, despite there existing free method. There is need to do something with this, add notice to docs, or make this method private.

P.S: You can repeat it by running this code, and specify the memory limit for java vm:
while(true){
    PointerBuffer pb = PointerBuffer.allocateDirect(9999);
    pb.free();
}

spasi

Hey KGAFT,

The name of this method is meant as a hint that it uses ByteBuffer.allocateDirect internally, which allocates a GC-managed ByteBuffer. The free method has this javadoc:

QuoteFrees the buffer allocation.

This method should not be used if the memory backing this buffer is not owned by the buffer.
All MemoryUtil methods that allocate explicitly-managed memory have the following note (or similar):

QuoteMemory allocated with this method must be freed with memFree.
ByteBuffer.allocateDirect, PointerBuffer.allocateDirect, BufferUtils methods and MemoryStack methods do not have such a note because, well, you don't have to do anything special to deallocate the returned buffer.

You may read Memory management in LWJGL for more details.