lua-users home
lua-l archive

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


Hi Ellie,
sorry if this question is too stupid / too basic.

But why do you want to check this in Lua? Especially if you anyway are
coding in C? The memory heap is managed by your C memory allocator,
and this can be very different depending on compiler and system and
heap amount ... such heap managers can be really "very complex
animals" - I would usually recommend to invoke it as seldom as
possible (so only for large chunks of memory, at NOT so frequent
times..). And if the heap memory used by gc (see lua_gc GC_COUNT
result) approaches 50%-80% of heap, the user somehow should best
receive some "severe warning". But the maximum heap available I think
Lua GC can not know ... you have to check the C functions of your
memory allocator for this ... .

On Fri, Nov 12, 2021 at 12:44 PM ellie <el@horse64.org> wrote:
>
> 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.