lua-users home
lua-l archive

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

>>>>> "ellie" == ellie  <> writes:

 ellie> Hi everyone,
 ellie> I am currently scratching my head on how to solve this best:

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

Besides the approach already discussed, another solution to this is
to use the GC to clean up any leaks. With suitable helper functions
you could do something like:

    char **p = push_string_helper(L);
    *p = returns_some_allocated_thing();
    if (!*p)
        return luaL_error(L, "whatever");
    replace_string_helper(L, -1);
    return 1;

The idea is that push_string_helper would push a full userdata object
holding a pointer, with a __gc metamethod that does a free() on the
pointer if it is not null. Then the replace function would push the
string, null out the pointer, and replace the userdata object on the
stack with the new string.

(This is essentially your idea of having a global clean-up list, except
that it's using the existing lua GC to do all the work for you)