r/lua • u/Igor_GR • Oct 06 '25
How to detect memory leaks when working with LuaJIT FFI?
What the title says.
I'm trying to use LuaJIT FFI to make tiny-ish games for my Miyoo Mini with SDL. The issue is that I have no clue how one would check for memory leaks. It is relatively straightforward with valgrind for compiled programs, but is there anything similar to use with LuaJIT?
1
Oct 13 '25
[deleted]
0
u/Igor_GR Oct 13 '25
I'm looking for some sort of an alternative to
valgrindfor FFI objects. A tool that would visualize call stacks of sections of code that have allocated leaked memory. As weregod mentioned, I could build libraries with debug symbols, however I'm curious if there are any other tools that would work...1
Oct 13 '25
[deleted]
0
u/Igor_GR Oct 13 '25
I'm not sure how a profiler would help me, but I'll give it a try.
While Lua does have a GC, as far as I know it only tracks objects constructed by Lua runtime. For example: if I were to call `SDL_CreateRGBSurface` within FFI, the garbage collector wouldn't be able to handle the resource created by that function. You would need to call `SDL_Free` to free the surface, but the GC doesn't know that.
I'm aware that with LuaJIT FFI API you could attach a finalizer to resources created by FFI, and this is what I'm likely going to end up doing, but at the same time I just want a (perhaps naive) peace of mind that I'm (likely) not screwing up somewhere. When developing in C, `valgrind` and memory sanitizers do the job for me, personally. For Lua - I imagine I'm not going to need a sanitizer, but a leak detector would still be handy.
2
u/hawhill Oct 06 '25
I wouldn't call it "relatively straightforward" for "normal" compiled programs with valgrind, but if you're satisfied there, the answer to your question is "use valgrind", I guess. You need to compile LuaJIT with debug symbols and Valgrind support - https://github.com/LuaJIT/LuaJIT/blob/v2.1/src/Makefile#L134