printf("%s\n", lua_tostring(L, -1)); 遇到分段错误

Joh*_*ohn 1 lua

为什么此代码片段会遇到分段错误?

 luaL_dostring(L, "print('this is a test')");
 printf("%s\n", lua_tostring(L, -1));
Run Code Online (Sandbox Code Playgroud)

以下是错误消息和回溯:

程序收到信号 SIGSEGV,分段错误。strlen () at ../sysdeps/x86_64/strlen.S:106 106 ../sysdeps/x86_64/strlen.S: 没有这样的文件或目录。

Gre*_*een 5

您执行的块不返回任何内容。假设您调用 的那一刻堆栈是空的luaL_dostring,那么在您调用它之后它保持不变。这意味着当您调用 时lua_tostring(L, -1),您会针对空堆栈调用它,因此会遇到 SEGV:

lua_State * L = luaL_newstate();
luaL_openlibs(L);
// stack is empty
luaL_dostring(L, "print('this is a test')");
// stack is still empty
printf("%s\n", lua_tostring(L, -1)); // segmentation fault
Run Code Online (Sandbox Code Playgroud)

为了进行比较,您可以尝试:

luaL_dostring(L, "print('this is a test') return 'another string'");
printf("%s\n", lua_tostring(L, -1)); // prints: another string
Run Code Online (Sandbox Code Playgroud)

为防止此类错误,请始终检查要使用的值:

luaL_dostring(L, "print('this is a test')");
if (lua_isstring(L, -1))
   printf("%s\n", lua_tostring(L, -1)); // OK, line is not executed
Run Code Online (Sandbox Code Playgroud)

您还可以检查 的返回值lua_tolstring

const char * value = lua_tostring(L, -1);
if (NULL != value)
   printf("%s\n", value); // Also OK
Run Code Online (Sandbox Code Playgroud)