emscripten-core / emscripten-core/emscripten
Memory leak in GL tables when recreating entities such as buffers
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
# 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;
};
}
```
Contributor guide
Assessment
This issue has not been assessed yet.