Memory Leak Caused By IntBuffer [SOLVED]

Started by TLHPoE, July 04, 2015, 01:02:13

Previous topic - Next topic

TLHPoE

Edit: Being the smart person I am, I overlooked the fact that there is indeed a window resize callback.



I have run into a problem while getting the frame buffer size. While the code I'm using works, it creates a memory leak. In my method, I store the width and height into an integer array and then return it. It is called once every time a frame is rendered. After that, it isn't called until the next frame is rendered.

Method:
public int[] getWindowSize() {
		int[] size = new int[2];

		IntBuffer widthBuffer = BufferUtils.createIntBuffer(1), heightBuffer = BufferUtils.createIntBuffer(1);

		GLFW.glfwGetFramebufferSize(window, widthBuffer, heightBuffer);

		size[0] = widthBuffer.get();
		size[1] = heightBuffer.get();

		return size;
	}


Where I call it:
public void preRender() {
		int[] size = getWindowSize();
		
		GL11.glViewport(0, 0, size[0], size[1]);
		
		GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
		GL11.glMatrixMode(GL11.GL_PROJECTION);
	}


Things I've tried:

  • Setting the size field to null afterwards
  • Using System#gc
  • Using Buffer#clear
  • Using Buffer#flip
  • Using Buffer#clear and then Buffer#flip
  • Using Buffer#flip and then Buffer#clear

Cornix

I am sorry, but I do not see a memory leak anywhere.
Perhaps you are mistaken and what you actually mean is that you produce unnecessary garbage?
In that case you could simply safe the IntBuffers and re-use them instead of throwing them away and creating them anew.

xsupermetroidx

Do not create buffers via BufferUtils on every invocation of a method. Store the buffer and reuse it. Problem solved.

spasi

Indeed, the correct way to handle this is via the window size callback. Or better, the framebuffer size callback; it is a different callback that will return different values on HiDPI displays (e.g. retina MacBooks).

(slightly off-topic)
A easy way to avoid unnecessary allocations in methods like getWindowSize above, is this:

public IntBuffer getFramebufferSize() {
	IntBuffer size = BufferUtils.createIntBuffer(2); // 1 allocation instead of 3

	nglfwGetFramebufferSize(window, memAddress(size), memAddress(size) + 4); // Note the 'n'. memAddress is in org.lwjgl.system.MemoryUtil.

	return size;
}

// Usage
IntBuffer size = getFramebufferSize();
glViewport(0, 0, size.get(0), size.get(1));