Warm tip: This article is reproduced from serverfault.com, please click
lua

lua-printf(“%s \ n”,lua_tostring(L,-1));

(lua - printf("%s\n", lua_tostring(L, -1)); meets a segmentation fault)

发布于 2020-12-01 09:15:12

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

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

这是错误消息和回溯:

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

Questioner
John
Viewed
0
Green 2020-12-02 00:41:17

你执行的块不返回任何内容。假设你在调用时栈为空,则在调用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

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

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

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

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

你还可以检查的返回值lua_tolstring

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