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

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

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

以下为错误信息和回溯:

程序收到 SIGSEGV 信号,分段错误。strlen() 在 ../sysdeps/x86_64/strlen.S 中, 106 ../sysdeps/x86_64/strlen.S: 无此文件或目录。

点赞
用户4984564
用户4984564

我认为是因为在 Lua 代码完成后栈顶没有字符串。

2020-12-01 09:21:08
用户4567755
用户4567755

执行的代码块并没有返回任何值。假定在你调用 luaL_dostring 函数时,堆栈为空,那么在调用该函数后堆栈仍为空。这意味着当你调用 lua_tostring(L, -1) 时,你是在一个空的堆栈上调用它,因此会遇到 SEGV:

lua_State * L = luaL_newstate();
luaL_openlibs(L);
// 堆栈为空
luaL_dostring(L, "print('this is a test')");
// 堆栈仍为空
printf("%s\n", lua_tostring(L, -1)); // 发生段错误

作为比较,你可以尝试:

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

为了防止这样的错误,一定要检查你想要使用的值:

luaL_dostring(L, "print('this is a test')");
if (lua_isstring(L, -1))
   printf("%s\n", lua_tostring(L, -1)); // OK,该行不执行

你也可以检查 lua_tolstring 的返回值:

const char * value = lua_tostring(L, -1);
if (NULL != value)
   printf("%s\n", value); // OK,同样可以正常输出
2020-12-01 12:20:43