ByteBuffers and Memory

Hi guys,

I just want to make sure that I am using Java Buffer objects in the correct way. Through most of my code, I have used the following method to fill a Buffer object from an array of data:


private FloatBuffer getFloatBuffer(float[] data)
{
    FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
    buffer.put(data);
    buffer.flip();
    return buffer;
}

However, I found a tutorial that describes how to use LWJGL’s STB binding to load a texture into openGL. I have included the code below which shows the process of creating and filling a byte buffer with image data via STB.


public void loadTexture(String filepath)
{
    ByteBuffer imageData;

    try (MemoryStack stack = MemoryStack.stackPush())
    {
        IntBuffer w = stack.mallocInt(1);
        IntBuffer h = stack.mallocInt(1);
        IntBuffer comp = stack.mallocInt(1);

        imageData = stbi_load(filepath, w, h, comp, 4);
    }

   // do openGL texure stuff
    
    MemoryUtil.memFree(imageData);
}

At the end of this function, the LWJGL memory util class is used to free the image data from memory, which is what causes confusion. Why does this Buffer’s memory need to be freed manually? Should I also be doing this with the Buffer objects being created in my first code sample?

Also, why use the MemoryStack class in the try statement? What would be the consequences of creating standard IntBuffers without the aid of this utility?