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

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

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

Why this code snippet encounter a segmentation fault?

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

Here are the error message and backtrace:

Program received signal SIGSEGV, Segmentation fault. strlen () at ../sysdeps/x86_64/strlen.S:106 106 ../sysdeps/x86_64/strlen.S: No such file or directory.

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

The chunk that you execute doesn't return anything. Assuming that your stack is empty at the moment you call luaL_dostring, it stays the same way after you call it. This means that when you call lua_tostring(L, -1), you call it against an empty stack and so SEGV is encountered:

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

For comparison you can try:

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

To prevent such errors, always check values you want to use:

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

You can also check the return value of lua_tolstring:

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