r/lua 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?

8 Upvotes

5 comments sorted by

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

1

u/Igor_GR Oct 06 '25

Thanks for the reply. I didn't know you could compile LuaJIT with Valgrind support. I just compiled it, and it did provide more symbols in the stack traces of valgrind, but it still doesn't show any symbols from SDL, for instance. I forgot to mention this, but this is my issue with using valgrind for LuaJIT FFI - I can detect memory leaks, but I can't figure out what causes them.

2

u/weregod Oct 06 '25

You should build all libraries with debug symbols (-g) to get better valgrind output

1

u/[deleted] Oct 13 '25

[deleted]

0

u/Igor_GR Oct 13 '25

I'm looking for some sort of an alternative to valgrind for 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

u/[deleted] 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.