DEV Community

Cover image for Analyze Lua Memory Leak With Systemtap
jinhua luo
jinhua luo

Posted on

Analyze Lua Memory Leak With Systemtap

The memory used by lua codes is managed by the GC, not calling malloc/free directly. The luajit GC uses mark-and-sweep algorithm. In simple words, it will links all gc objects in a global list. When the memory is in pressure, it would trigger recycle procedures. Note that because of single-threading design, the GC is interspersed in the flow of lua codes (either compiled
or interpretered), e.g. after string allocation. GC would try to check if the gc object is still in used, e.g. as an upvalue, reside in a stack. The GC would sweep all dangling gc objects at the end, and the corresponding memory would be freed and returned to C allocator.

In luajit, lj_alloc_malloc and lj_alloc_realloc would allocate gc objects, and lj_alloc_free would free them. So naturally, we could trace the invocations of these functions to check memory leak.

Note that triggering gc is a bit uncertain and the gc steps would be splited in different time slices. So it would not free unused memory immediately. Moreover, the lua codes may use caches. So it's necessary to check the codes to distinguish the real memory leak.

Please check my blog site:

http://luajit.io/post/2022/analyze-lua-memory-leak-with-systemtap/

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

Top comments (0)

Postmark Image

The email service that speaks your language

Whether you code in Ruby, PHP, Python, C#, or Rails, Postmark's robust API libraries make integration a breeze. Plus, bootstrapping your startup? Get 20% off your first three months!

Start free

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay