Race condition in garbage collection

73 views
Skip to first unread message

Stefano Cossu

unread,
Nov 21, 2025, 7:46:17 AM (6 days ago) Nov 21
to lua-l
Hello,
I am getting a segfault on a Lua binding to a C library I wrote. I
traced down the segfault to garbage collection, when two objects that
depend on one another are freed in the wrong order.

I have a Graph object and a GraphIterator object. The latter is a C
structure with a pointer to a Graph. The segfault happens when the __gc
function for the GraphIterator tried to access the Graph after this has
been garbage-collected already.

To avoid this race condition, I have been thinking about adding a Lua
reference to the original Graph in the newly created GraphIterator; I
suppose that then the garbage collector will have to free the
GraphIterator first.

This was my first attempt, which did not succeed:

// Create an iterator from a graph
static int l_graph_add_init (lua_State *L)
{
VOLK_Graph *gr = *(VOLK_Graph **)luaL_checkudata (L, 1, "VOLK.Graph");

VOLK_GraphIterator **it_p = lua_newuserdata (L, sizeof *it_p);
luaL_getmetatable (L, "VOLK.GraphIterator");
lua_setmetatable (L, -2);

lua_pushvalue (L, 1);
lua_setfield (L, -2, "graph"); // Add the "graph" key to the iterator

*it_p = VOLK_graph_add_init (gr);
LUA_NLCHECK (*it_p, "Error creating graph iterator.");

return 1;
}

This won't work, as the Lua interpreter tells me that I'm trying to
index a userdata value. I think I still have a confused understanding of
how Lua entities are created in the C API. What would be an effective
way to ensure that the dependent object is freed before the one it
points to?

Thanks,
Stefano
OpenPGP_0x1716A1B35E826596.asc
OpenPGP_signature.asc

ppp vvv

unread,
Nov 21, 2025, 11:54:27 AM (6 days ago) Nov 21
to lua-l
Hi,
You should use lua_setiuservalue to store Graph reference in the GraphIterator userdata.
пятница, 21 ноября 2025 г. в 13:46:17 UTC+1, Stefano Cossu:

Stefano

unread,
Nov 21, 2025, 1:53:54 PM (6 days ago) Nov 21
to lua-l
That works like a charm and the garbage collection is now happening in the correct order. Thanks!
Reply all
Reply to author
Forward
0 new messages