lua-users home
lua-l archive

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


It was thus said that the Great ellie once stated:
> 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.

  If you have control over returns_some_allocated_thing(), you might want to
look at luaL_Buffrer() and the various luaL_add*() functions, as well as
luaL_prepbuff*() functions.

  -spc