lua-users home
lua-l archive

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


I am hunting a ghost.  This is my ghost:

Previously, we used the following construct in C code:

p = malloc(sizeof int)
*p = 42

/* Do a Lua API call that might error (longjmp) out */

free(p)

Daurnimator rightfully pointed out that this would leak memory
if the Lua API call actually errors out and we changed that to:

p = lua_newuserdate(L, sizeof int)
*p = 42

/* Do a Lua API call that might error (longjmp) out */

Withe the latter, however, we see sporadic program crashes,
valgrind emits all kind of "Invalid write of size 8" error messages
and our customers pick up the phone to call us...

Is it possible that a userdata value get garbage collected when
it has been created, leading to a dangling pointer?

What would happen if I luaL_ref() the userdata value directly
after creating it?  To my understanding it would then be
locked in memory forever, unless I unref it?

So the following would leak the memory as well, if the API call
errors out?

p = lua_newuserdate(L, sizeof int)
l = luaL_ref(L, -1)
*p = 42

/* Do a Lua API call that might error (longjmp) out */

luaL_unref(l)

(The code in question is the Lua PostgreSQL interface on
github.com/arcapos/luapgsql, the functions conn_execPrepared()
and get_sql_params())

Thanks for any ideas,
Marc