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.
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
Thank you so much. The output message(i.e: 'this is a test') has never been pushed to the stack (when invoking "print('this is a test')"), it's just printed to the stdout by the
fwrite()
(invoked bylua_writeline()
) function. Am I right?@John, Yes, pretty much, on top of that print/
luaB_print
doesn't push anything to stack at all. Try:type(print("whatever"))
and compare withtype(nil)
.I don't understand the purpose of comparing
type(print("whatever"))
andtype(nil)
. And I get error messages when invokingtype(print("whatever"))
.Here are the outputs and error messages:"> type(print("whatever")) whatever stdin:1: bad argument #1 to 'type' (value expected) stack traceback: [C]: in function 'type' stdin:1: in main chunk [C]: in ?"@John, Point was to illustrate that behaviour differs between returning
nil
and returning nothing at all. And it's worth remembering thatprint
doesn't return anything as it can cause problems in some very rare cases. From Lua side it doesn't happen often asnil
is almost omnipresent andtostring
handles all types, but when you use C API you may shoot yourself in a foot.