lua-users home
lua-l archive

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


Hi everyone,

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;

I have this pattern in my code a lot, and the only way I can think of to avoid leaks is to have some global clean-up list, to add p right before a push, and to remove it again if the push worked and I can clean it up normally. However, this seems both cumbersome and error-prone to maintain.

This is why I wondered if there is an alternate function like the following, where I could hypothetically decide how to handle the OOM myself:

char *p = returns_some_allocated_thing();
if (!p) {
    oom:
    lua_pushstring("out of memory");
    return lua_error(l);
}
int pushresult = lua_trypushstring(l, p));
free(p);
if (!pushresult) goto oom;
return 1;

This would seem to me like a clean way to solve it, but so far I haven't spotted such a function in the Lua manual. If there isn't one, does someone know if lua_pushstring can be wrapped to catch the setjmp to implement this without possibly messing up/unrolling the lua_State stack? Or is there a chance such a function might be added to Lua officially some day? Don't know how others would like it, but I'd love to use it.

I'm kind of a fan of not-crash not-leak out of memory handling in my own code, especially on MS Windows, but I do find it difficult right now with Lua's API in this corner case. Any ideas appreciated.

Regards,

Ellie

PS: this might even be interesting on Linux where things usually are shot down by the OOM killer, e.g. when using a custom allocator with a lower limit than all remaining free system memory.