#22425·emscripten

Memory leak in GL tables when recreating entities such as buffers

Author: jim-risenCreated Aug 21, 2024Updated Sep 25, 2026

Memory leak in GL tables when recreating entities

Version of emscripten/emsdk: 3.1.40

The issue was noticed when creating/deleting WebGL buffers with glGenBuffers. The GL.buffers array would grow and never shrink.
However, this is probably not unique for this array, but most likely appears in other "tables" within GL.

The root cause appears to be in the table entry insertion logic, specifically GL.getNewId,
which only increases the table sizes and fills them with null's.
https://github.com/emscripten-core/emscripten/blob/02577a5bb778ff6b1b85da18569a008ed15e15b5/src/library_webgl.js#L308-L316


Currently, it seems I was able to resolve the issue by applying a workaround with custom implementation using --post-js:

javascript
// an override to fix a memory leak caused by growing buffer arrays in GL
if (GL) {
  GL.getNewId = function (table) {
    // this seems to be required
    GL.counter++;

    var len = table.length;

    // handle a special case according to the comment at https://github.com/emscripten-core/emscripten/blob/02577a5bb778ff6b1b85da18569a008ed15e15b5/src/library_webgl.js#L245
    if (len === 0) {
      return 1;
    }

    // find available slot index
    for (var i = 1; i < len; ++i) {
      if (table[i] === null) {
        return i;
      }
    }

    // or add a new one
    return len;
  };
}

Source: emscripten-core/emscripten