lua-users home
lua-l archive

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


Thanks for the response, that was quick!

I'm wondering though, couldn't the lua_pushcfunction itself cause an out of memory error too? My apologies if I'm reading it wrong, but to me it seems like it moves the problem around with the same outcome - that the "ppushstring" might OOM setjmp like "lua_pushstring", without allowing me a more controlled recovery to clean things up.

On 11/12/21 14:21, Roberto Ierusalimschy wrote:
I am currently scratching my head on how to solve this best:

char *p = returns_some_allocated_thing();
if (!p) {
     lua_pushstring("out of memory");
     return lua_error(l);
}
lua_pushstring(l, p);  // if this has an OOM error, p leaks!
free(p);
return 1;

One way to solve this is to do the lua_pushstring inside a pcall. You
can pass 'p' as a light userdata in the pcall. Something roughly like
this:

static int auxpushstr (lua_State *L) {
   char *p = (char *)lua_touserdata(L, 1);
   lua_pushstring(L, p);
   return 1;
}

/* protected push string */
static int ppushstring (lua_State *L, const char *s) {
   int status;
   lua_pushcfunction(L, &auxpushstr);
   lua_pushlightuserdata(L, s);
   status = pcall(L, 1, 1, 0);
   return status;
}


-- Roberto