首页 > 解决方案 > printf("%s\n", lua_tostring(L, -1)); 遇到分段错误

问题描述

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

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

以下是错误消息和回溯:

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

标签: lua

解决方案


您执行的块不返回任何内容。假设你调用的那一刻你的堆栈是空的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

推荐阅读