【问题标题】:Unknown error in a C++ programC++ 程序中的未知错误
【发布时间】:2012-10-31 01:28:43
【问题描述】:
void change_degree(vector<int> &nodes, map<int, vector<int> > &edges, int vertex){
    map<int, vector<int> >::iterator ite;
    ite = edges.find(vertex);
    vector<int> temp = (*ite).second;
    vector<int>::iterator it;
    for(it = temp.begin(); it != temp.end(); it++){
        cout << *it;
        if(nodes[*it + 1] > 1)
            nodes[*it + 1]++;
    }
}  

这个函数产生错误

*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x09c930e0 ***  

谁能告诉我为什么会出现它以及它意味着什么? 提前致谢。

【问题讨论】:

  • vertex 可以不在edges 中吗?如果不是,则该函数中唯一可能的无效访问是nodes[*it + 1]
  • gdbvalgrind 打招呼!
  • 顶点存在边。
  • 这可能意味着内存滥用正在发生,并且正在释放未分配的东西,或者在附近。如果有问题,请使用valgrind 查找问题。查看malloc() 的手册页,了解您有哪些调试选项。

标签: c++ pointers gcc stl iterator


【解决方案1】:

嗯,我看到的一个问题是您没有检查vertex 是否真的在edges 中找到。您可能正在取消引用您不拥有的内存。

void change_degree(vector<int> &nodes, map<int, vector<int> > &edges, int vertex){
    map<int, vector<int> >::iterator ite = edges.find(vertex);
    if (ite != edges.end()) {  // <-- this is what you're missing
        vector<int> temp = (*ite).second;  // <-- this is probably where you're dying
        vector<int>::iterator it;
        for(it = temp.begin(); it != temp.end(); it++){
            cout << *it;
            if(nodes[*it + 1] > 1)  // <-- you could also be crashing here
                nodes[*it + 1]++;
        }
    }
}

下一次,尝试通过 GDB 运行您的应用,并检查您的堆栈跟踪。

编辑:另一种可能性是您对nodes 的索引不正确。检查nodes[*it + 1] 是否有效。

【讨论】:

  • 正如我在 cmets 中所写,顶点存在于边中,即使在检查了条件 ite!= edges.end() 之后,它也会给出相同的错误
  • 感谢它提供的节点 [*it + 1]。谢谢@moswald
猜你喜欢
  • 2015-05-29
  • 1970-01-01
  • 2016-11-18
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2012-11-10
  • 2013-12-21
  • 2015-03-28
相关资源
最近更新 更多