lua - 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: 没有这样的文件或目录。
解决方案
您执行的块不返回任何内容。假设你调用的那一刻你的堆栈是空的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
推荐阅读
- docusignapi - 如何删除 docusign 应用程序和 API 页面上的应用程序?
- python - Discord.py 获取用户返回无
- python-3.x - 在 Numpy 中快速将图像分解为子图像
- javascript - Google Data Studio API 问题中的分步配置
- javascript - JqueryDatatable 自定义按列过滤
- python - python - 如何在python中使用plotly将更多等高线添加到contourplot中?
- c - 是否可以通过 GType 扩展 GKeyFile 以保存私有·origin· 枚举字段?
- python - PDFminer - 有没有办法从 pdfminer 将 pdf 转换为 html?
- ubuntu - 在 Ubuntu 中为 CxOracle 插入查询减速
- c# - 从 Unity 的打开文件面板中选择文件后,UnityWebRequest 未完成