C++ 带字符串的地图坏了吗?

C++ 带字符串的地图坏了吗?,c++,debugging,lua,segmentation-fault,C++,Debugging,Lua,Segmentation Fault,对。我看不出我做错了什么 映射为:string,int 方法是这样的 bange::function::Add(lua_State *vm){ //userdata, function if (!lua_isfunction(vm, 2)){ cout << "bange: AddFunction: First argument isn't a function." << endl; return false;} void *pfunct

对。我看不出我做错了什么

映射为:string,int

方法是这样的

bange::function::Add(lua_State *vm){  
 //userdata, function  
 if (!lua_isfunction(vm, 2)){  
  cout << "bange: AddFunction: First argument isn't a function." << endl;  
  return false;}  
 void *pfunction = const_cast<void *>(lua_topointer(vm, 2));  
 char key[32] = {0};  
 snprintf(key, 32, "%p", pfunction);  
 cout << "Key: " << key << endl;  
 string strkey = key;  
 if (this->functions.find(strkey) != this->functions.end()){  
     luaL_unref(vm, LUA_REGISTRYINDEX, this->functions[strkey]);}  
 this->functions[strkey] = luaL_ref(vm, LUA_REGISTRYINDEX);  
 return true;  
我需要这个来收集垃圾。现在,从Lua访问
bange::function::Add

static int bangefunction_Add(lua_State *vm){
    //userdata, function
    bange::function *function = reinterpret_cast<bange::function *>(lua_touserdata(vm, 1));
    cout &lt&lt "object with bange::function: " &lt&lt function << endl;
    bool added = function->bange::function::Add(vm);
    lua_pushboolean(vm, static_cast<int>(added));
    return 1;
}
我终于注意到问题是

bange::function*function=reinterpret_cast(lua_-tuserdata(vm,1))


因为对象是
bange::scene
和no
bange::function
(我承认,这是指针损坏),这似乎更像是一个代码设计问题。所以这在某种程度上解决了。谢谢大家。

因为strkey是唯一可以比较的字符串,所以它一定是问题的根源,它来自堆栈上的char[]。我会先把它处理掉

std::stringstream str;
str << pfunction;
string strkey = str.str();
std::stringstream str;

str此代码可能没有问题

当代码试图读取或写入未映射到进程的内存时,会发生分段错误。它发生的点可能与错误所在的位置无关

在程序中的某个时刻,在出现分段错误之前,一些代码对堆进行了分段。这可能是

  • 访问已删除/释放的指针
  • 覆盖数组的边界
  • 将对象强制转换为错误类型并使用它
  • 所有这些东西都不必立即崩溃——它们可能会默默地破坏内存。在以后的某个时候,当使用该内存时,它也可能不会崩溃(只是默默地损坏其他内存)。在某一点上,您会崩溃,但这一点可能与问题完全无关

    调试的策略是使第一个损坏崩溃。有几种方法可以做到这一点

  • 使用调试堆。以下是在Linux上使用GCC的一些可能性

  • 瓦尔格林:


  • 您的代码在哪一行崩溃?
    static int bangefunction_Add(lua_State *vm){
        //userdata, function
        bange::function *function = reinterpret_cast<bange::function *>(lua_touserdata(vm, 1));
        cout &lt&lt "object with bange::function: " &lt&lt function << endl;
        bool added = function->bange::function::Add(vm);
        lua_pushboolean(vm, static_cast<int>(added));
        return 1;
    }
    
    bange::function::function(){  
        string test("test");  
        this->functions["test"] = 2;  
    }  
    
    std::stringstream str;
    str << pfunction;
    string strkey = str.str();