Zack Lee
Zack Lee

Reputation: 3074

Calling lua_getglobal() crashes unless followed by lua_pop()

I just figured out my app sometimes crashes when lua_getglobal(L, "name"); is called many times.

I tried placing lua_pop(L, 1); after lua_getglobal(L, "name"); and it no longer crashes.

Can calling lua_getglobal(L, "name"); many times cause memory leaks?

Does anybody have a clue why my app crashes without lua_pop(L, 1);?

Upvotes: 1

Views: 1567

Answers (1)

Henri Menke
Henri Menke

Reputation: 10939

Lua has a (implementation-defined) limited stack size. If you keep pushing onto the stack without ever popping, the stack will be full at some point and trying to push more will crash your program.

If you check the documentation for lua_getglobal you'll find “Pushes onto the stack the value of the global”. You are responsible for removing it, either calling a function which implicitly pops it (e.g. lua_pcall) or by explictly popping it with lua_pop.

#include <iostream>

#include <lua.hpp>

int main() {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    if (luaL_dostring(L, "name = 'Zack Lee'") != 0) {
        std::cerr << "lua:" << lua_tostring(L, -1) << '\n';
        lua_close(L);
        return 1;
    }

    for (int i = 0; i < 200; ++i) {
        lua_getglobal(L, "name");
        std::cout << i << ' ' << lua_tostring(L, -1) << '\n';
      //lua_pop(L, 1);
    }

    lua_close(L);
}
$ clang++ -Wall -Wextra -Wpedantic -I/usr/include/lua5.2/ test.cpp -llua5.2
$ ./a.out
0 Zack Lee
<...snip...>
41 Zack Lee
Segmentation fault

If I uncomment the lua_pop line, it works as expected.

You can also resize the Lua stack, but this has already been answered elsewhere.

Upvotes: 7

Related Questions