lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I have the following situation: a C function that is called from Lua
to retrieve a variable-size block of data from somewhere in my
application. In code:

static int get_data(lua_State* L)
{
 char* buffer;
 int n = luaL_optint(L, 1, 512 /* some arbitrary default value */);

 buffer = malloc(n);
 if (!buffer)
   return luaL_error(L, "malloc() failed");
 n = read_data(buffer, n);
 lua_pushlstring(L, buffer, n);
 free(buffer);
 return 1;
}

A potential problem I see with this is that if lua_pushlstring()
raises an error I leak the buffer. The chance that this happens is
rather small but since this code will run on an embedded platform I
really can't afford it.

I was looking at the luaL_Buffer mechanism. I know it is intended for
collecting lots of small strings but luaL_prepbuffer() seems useful
for my scenario. Could I use this to allocate space and pass the
pointer to the read_data() function, then do a luaL_addsize() and
luaL_pushresult()? Is it guaranteed that if some Lua function raises
an error the luaL_Buffer memory is freed?

--
Dirk