From 6af46f9aa5a2966e5aa93d69d53893b8976918ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20Andr=C3=A9=20Tanner?= Date: Thu, 1 Jun 2017 22:31:23 +0200 Subject: vis-lua: avoid string memory leaks in error case The function lua_pushstring can throw an error, meaning it will setjmp(3) out thereby leaking the allocated memory. By using lua_newuserdata we let Lua free the memory during a GC run. --- vis-lua.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/vis-lua.c b/vis-lua.c index 8a0f0dc..2a7479d 100644 --- a/vis-lua.c +++ b/vis-lua.c @@ -2157,12 +2157,11 @@ static int file_lines_iterator_it(lua_State *L) { return 0; size_t end = text_line_end(file->text, *start); size_t len = end - *start; - char *buf = malloc(len); + char *buf = lua_newuserdata(L, len); if (!buf && len) return 0; len = text_bytes_get(file->text, *start, len, buf); lua_pushlstring(L, buf, len); - free(buf); *start = text_line_next(file->text, end); return 1; } @@ -2192,12 +2191,11 @@ static int file_content(lua_State *L) { if (!text_range_valid(&range)) goto err; size_t len = text_range_size(&range); - char *data = malloc(len); + char *data = lua_newuserdata(L, len); if (!data) goto err; len = text_bytes_get(file->text, range.start, len, data); lua_pushlstring(L, data, len); - free(data); return 1; err: lua_pushnil(L); @@ -2287,12 +2285,11 @@ static int file_lines_index(lua_State *L) { size_t end = text_line_end(txt, start); if (start != EPOS && end != EPOS) { size_t size = end - start; - char *data = malloc(size); + char *data = lua_newuserdata(L, size); if (!data && size) goto err; size = text_bytes_get(txt, start, size, data); lua_pushlstring(L, data, size); - free(data); return 1; } err: -- cgit v1.2.3