【问题标题】:declare a vector variable in c module cause segmentation fault在 c 模块中声明向量变量导致分段错误
【发布时间】:2019-01-07 16:39:32
【问题描述】:

我在 lua(5.1) 中测试调用 c/c++ 模块。没有向量,代码运行良好。但是当我包含 stl/vector 并在函数添加中声明一个向量变量时,程序会导致分段错误。

libvec.so 代码

#include <vector>
#include <list>
#include "lua.hpp"
#include <algorithm>
#include <iostream>
#include <string>
#include <map>

extern "C" int add(lua_State* L)
{
    double op1 = luaL_checknumber(L, 1);
    double op2 = luaL_checknumber(L, 2);
    //std::vector<double> vec;
    //vec.push_back(op1);
    //vec.push_back(op2);
    //lua_pushnumber(L, vec[0]+vec[1]);
    lua_pushnumber(L, op1 + op2);
    return 1;
}

static luaL_Reg mylibs[] = {
    {"add", add}
};

extern "C" int luaopen_libvec(lua_State *L){
    luaL_register(L, "libvec", mylibs);
    return 1;
}

test.lua 代码:

local vec = require 'libvec'
print(vec.add(1,212))

然后我尝试 gdb lua/运行 test.lua,然后得到

strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
(gdb) bt
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
#1  0x000000000040596e in lua_setfield ()
#2  0x0000000000412f75 in luaL_openlib ()
#3  0x00007ffff6e8e531 in luaopen_libvec () from ./libvec.so
#4  0x00000000004080d8 in luaD_precall ()
#5  0x00000000004084e4 in luaD_call ()
#6  0x0000000000405c95 in lua_call ()
#7  0x000000000041dcaa in ll_require ()
#8  0x00000000004080d8 in luaD_precall ()
#9  0x00000000004116d2 in luaV_execute ()
#10 0x000000000040852d in luaD_call ()
#11 0x000000000040782b in luaD_rawrunprotected ()
#12 0x000000000040868b in luaD_pcall ()
#13 0x0000000000405d26 in lua_pcall ()
#14 0x0000000000403ecc in docall ()
#15 0x00000000004048a9 in pmain ()
#16 0x00000000004080d8 in luaD_precall ()
#17 0x00000000004084e4 in luaD_call ()
#18 0x000000000040782b in luaD_rawrunprotected ()
#19 0x000000000040868b in luaD_pcall ()
#20 0x0000000000405db5 in lua_cpcall ()
#21 0x0000000000403b94 in main ()

我有测试声明 std::map 并且在 std::string 运行良好时也崩溃了......

【问题讨论】:

  • 你传递给 vec.add() 的是什么?它在期待什么?
  • @mfromla 只需运行 lua test.lua

标签: c++ lua


【解决方案1】:

来自luaL_register的文档:

任何 luaL_Reg 数组都必须以一个标记条目结尾,其中 name 和 func 都为 NULL。

这里不是这种情况,我可以想象添加std::vector 方法来推开一些之前碰巧存在的空字节。

tl;dr:将 {NULL, NULL} 条目添加到 myLibs

【讨论】:

    【解决方案2】:

    来自文档https://www.lua.org/manual/5.1/manual.html#luaL_ref

    由 luaL_register 注册的函数数组的类型。 name 是函数名,func 是指向函数的指针。任何 luaL_Reg 数组都必须以一个标记条目结束,其中 name 和 func 都为 NULL。

    luaL_register 正在遍历您的数组,直到找到哨兵值,因为它没有找到它读取的数组末尾的值。

    正确的数组是:

    static luaL_Reg mylibs[] = {
        {"add", add},
        {NULL, NULL}
    };
    

    【讨论】:

      猜你喜欢
      • 2011-05-31
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2022-01-03
      相关资源
      最近更新 更多