简体   繁体   中英

SIGSEGV error in some lua/c++ code

The following code end in a SIGSEGV error:

extern "C" {
    #include "lua/lua.h"
    #include "lua/lualib.h"
    #include "lua/lauxlib.h"
}

int main( int argc, char *argv[] )
{
    lua_State *L;
    luaL_openlibs(L);
    lua_close(L);
    return 0;
}

Gdb gives me the following:

(gdb) run
Starting program: d:\Dropbox\cpp\engine\bin\main.exe
[New Thread 7008.0x1df8]

Program received signal SIGSEGV, Segmentation fault.
0x6d781f30 in lua_pushcclosure () from d:\Dropbox\cpp\engine\bin\lua52.dll
(gdb) where
#0  0x6d781f30 in lua_pushcclosure () from d:\Dropbox\cpp\engine\bin\lua52.dll
#1  0x6d79329e in luaL_requiref () from d:\Dropbox\cpp\engine\bin\lua52.dll
#2  0x6d79bdee in luaL_openlibs () from d:\Dropbox\cpp\engine\bin\lua52.dll
#3  0x004013a6 in main (argc=1, argv=0x702fc8) at main.cpp:10
(gdb)

You have to do create a new lua state before opening the lib ( luaL_openlibs(L); ), like this:

L = luaL_newstate();

You get the segmentation fault because you have an unitialized pointer, dereferencing it (which is what the lib does) is undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM