From: Steinar H. Gunderson Date: Sat, 14 Nov 2015 16:40:14 +0000 (+0100) Subject: Fix a memory leak in the Lua code. X-Git-Tag: 1.0.0~122 X-Git-Url: https://git.sesse.net/?p=nageru;a=commitdiff_plain;h=ceb037cf9d77dbf83170c4dea5279edfa664e2c9 Fix a memory leak in the Lua code. --- diff --git a/theme.cpp b/theme.cpp index bd12590..f7ec8e8 100644 --- a/theme.cpp +++ b/theme.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include "image_input.h" @@ -37,6 +38,23 @@ namespace { vector live_inputs; +class LuaRefWithDeleter { +public: + LuaRefWithDeleter(mutex *m, lua_State *L, int ref) : m(m), L(L), ref(ref) {} + ~LuaRefWithDeleter() { + unique_lock lock(*m); + luaL_unref(L, LUA_REGISTRYINDEX, ref); + } + int get() const { return ref; } + +private: + LuaRefWithDeleter(const LuaRefWithDeleter &) = delete; + + mutex *m; + lua_State *L; + int ref; +}; + template int wrap_lua_object(lua_State* L, const char *class_name, Args&&... args) { @@ -501,14 +519,14 @@ Theme::get_chain(unsigned num, float t, unsigned width, unsigned height) exit(1); } lua_pushvalue(L, -1); - int funcref = luaL_ref(L, LUA_REGISTRYINDEX); // TODO: leak! + shared_ptr funcref(new LuaRefWithDeleter(&m, L, luaL_ref(L, LUA_REGISTRYINDEX))); lua_pop(L, 2); assert(lua_gettop(L) == 0); return make_pair(chain, [this, funcref]{ unique_lock lock(m); // Set up state, including connecting signals. - lua_rawgeti(L, LUA_REGISTRYINDEX, funcref); + lua_rawgeti(L, LUA_REGISTRYINDEX, funcref->get()); if (lua_pcall(L, 0, 0, 0) != 0) { fprintf(stderr, "error running chain setup callback: %s\n", lua_tostring(L, -1)); exit(1);