lua-users home
lua-l archive

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

> On May 9, 2016, at 3:37 AM, Marc Balmer <> wrote:
> I would like to open a discussion on best practices for preventing memory leaks in C programs using the Lua API.
> Consider the following code snippet:
> char *s = malloc(32);
> snprintf(s, 32, "bumblebee");
> lua_pushstring(L, s);
> free(s);
> lua_pushstring() could raise an error (e.g. under memory pressure) and then the subsequent free(s) would not be called, leaking the memory.
> One could use lua_newuserdata() instead of malloc, but this works only if the memory is allocated by our own code, it does not work where the memory is allocated e.g. by a third party library.
> So a possible way could be to create a metatable containing a __gc method, then allocating a small userdata value containging only a pointer to the allocated data. The __gc method could then free the memory, even if lua_pushstring() fails.
> Is it worth the effort?  How do others (you) handle this kind of possible errors?
> My personal take on this is, btw:  I don't care as I long as I don't reference NULL pointers.  If we are under memory pressure and functions like lua_pushstring() are starting to fail, we will be in much deeper trouble anyway soon... ymmv, opinions very welcome.
> - mb


If this is a project for yourself ... Do what you feel like.

If it is a library (or similar piece of software) that you will contribute to the en source world, you should make every effort to catch error conditions and do something sane with them.

Saying "we will be in deeper trouble soon" is not always an acceptable out. One of the strong attractions of Lua is that it can be ported to platforms with limited resources and/or primitive operating systems. If you want your library included in that port it then it must handle the error condition.

Frank Kastenholz