【问题标题】:c++ free(): invalid pointer error while path compression (union by rank)c ++ free():路径压缩时无效指针错误(按等级联合)
【发布时间】:2016-04-14 07:29:03
【问题描述】:

我查看了其他类似的问题,但无法找出此错误的原因。我正在编写一个 C++ 程序来实现 Kruskal 的最小生成树算法,使用 Union by rank 和路径压缩。 它正确打印 MST 的边缘,但包含路径压缩部分会导致此错误:

* `./kruskal' 中的错误:free():无效指针:0x0000000001650d00 *

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, pair<int,int> > pip;
typedef pair<int,int> pii;
class UnionFind {
    vector <int> parent,rank;
    public:
        UnionFind(int n){
            parent.resize(n);
            rank.resize(n);
            for (int i=0;i<n;i++) { //initialize all parents and ranks
                parent[i]=i;
                rank[i]=0;
            }
        }
        int find (int x){
            int root=x,y;
            while (parent[root]!=root) {
                root=parent[root];
            }
//uncommenting the following loop gives the error
            /*while (parent[x]!=root){ //path compression
                y=parent[x];
                parent[x]=root;
                x=y;
            }*/
            return root;
        }
        void unite (int x,int y) {
            x=find(x);
            y=find(y);
            if (rank[x]>=rank[y]){
                parent[y]=x;
                if (rank[x]==rank[y])
                    rank[x]++;
            }
            else parent[x]=y;
        }
};
int main() {
    int v1,v2,w,n,m;
    cout<<"Enter number of vertices, edges: ";
    cin>>n>>m;
    vector <pip> edges(m);
    UnionFind uf(n);
    cout<<"Enter edges in the form v1,v2,w: ";//w=length of edge
    for (int i=0;i<m;i++) {
        cin>>v1>>v2>>w;
        edges[i]=pip(w,pii(v1,v2));
    }
    sort (edges.begin(),edges.end()); //sort edges in increasing order or lengths
    cout<<"MST: edges \n";
    for (int i=0;i<m;i++){
        if (uf.find(edges[i].second.first)!=uf.find(edges[i].second.second)) {
            uf.unite (edges[i].second.first,edges[i].second.second);
            cout<<edges[i].second.first<<"--"<<edges[i].second.second<<endl;
        }
    }
    return 0;
}

通过查看 gdb 的回溯,它似乎是向量/类析构函数的问题:

(gdb) backtrace
#0  0x00007ffff74ab267 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:55
#1  0x00007ffff74aceca in __GI_abort () at abort.c:89
#2  0x00007ffff74eebf3 in __libc_message (do_abort=do_abort@entry=1, 
    fmt=fmt@entry=0x7ffff7607168 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007ffff74f6c09 in malloc_printerr (ptr=<optimized out>, 
    str=0x7ffff76032ba "free(): invalid pointer", action=1) at malloc.c:4965
#4  _int_free (av=<optimized out>, p=<optimized out>, have_lock=0) at malloc.c:3834
#5  0x00007ffff74fa83c in __GI___libc_free (mem=<optimized out>) at malloc.c:2950
#6  0x0000000000402cfc in __gnu_cxx::new_allocator<int>::deallocate (this=0x7fffffffdf58, 
    __p=0x618d00) at /usr/include/c++/5/ext/new_allocator.h:110
#7  0x0000000000402588 in __gnu_cxx::__alloc_traits<std::allocator<int> >::deallocate (__a=..., 
    __p=0x618d00, __n=10) at /usr/include/c++/5/ext/alloc_traits.h:185
#8  0x0000000000401ce6 in std::_Vector_base<int, std::allocator<int> >::_M_deallocate (
    this=0x7fffffffdf58, __p=0x618d00, __n=10) at /usr/include/c++/5/bits/stl_vector.h:178
#9  0x00000000004018a8 in std::_Vector_base<int, std::allocator<int> >::~_Vector_base (
    this=0x7fffffffdf58, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/stl_vector.h:160
#10 0x0000000000401498 in std::vector<int, std::allocator<int> >::~vector (this=0x7fffffffdf58, 
    __in_chrg=<optimized out>) at /usr/include/c++/5/bits/stl_vector.h:425
#11 0x000000000040140b in UnionFind::~UnionFind (this=0x7fffffffdf40, __in_chrg=<optimized out>)
    at kruskal.cpp:7
#12 0x0000000000401023 in main () at kruskal.cpp:47

有人可以解释一下当我在循环中包含路径压缩时会发生什么中断吗?

编辑:给出错误的示例输入:

10 14
1 5 1
1 8 10
2 3 2
4 1 4
4 8 1
5 6 3
6 2 1
6 3 3
6 7 7
6 9 1
8 5 5
8 9 9
9 10 2
10 7 1

【问题讨论】:

  • 至少出于调试目的,而不是vector::operator[],使用vector::at() 方法并尝试捕获异常。它可能超出矢量范围。
  • 其次while (parent[root]!=root) 这是另一个可疑代码。您的算法可能会确保 root 始终是有效索引,但它可能不是。添加root &lt; parent.size() 和可能的root &gt;= 0(取决于您如何获得root)检查或类似的东西。 while (parent[x]!=root) 也一样
  • 这个输入给了我错误:10 14 1 5 1 1 8 10 2 3 2 4 1 4 4 8 1 5 6 3 6 2 1 6 3 3 6 7 7 6 9 1 8 5 5 8 9 9 9 10 2 10 7 1 这是一个有 10 个顶点和 14 条边的图,对于此评论的格式错误,请见谅。
  • @bolov 谢谢你,你说得对,root 超出了范围。正如 MikeCAT 在他的回答中指出的那样,我正在访问超出范围的索引。

标签: c++ union-find invalid-pointer


【解决方案1】:

只有 10 个节点,但有 9-10 条边和 10-7 条边,所以您访问的向量超出范围。在存储之前尝试将 1-origin 输入转换为 0-origin。

试试

for (int i=0;i<m;i++) {
    cin>>v1>>v2>>w;
    edges[i]=pip(w,pii(v1-1,v2-1));
}

而不是

for (int i=0;i<m;i++) {
    cin>>v1>>v2>>w;
    edges[i]=pip(w,pii(v1,v2));
}

cout<<(edges[i].second.first+1)<<"--"<<(edges[i].second.second+1)<<endl;

而不是

cout<<edges[i].second.first<<"--"<<edges[i].second.second<<endl;

【讨论】:

  • 谢谢迈克,当我开始写它时,我正计划对此进行调整,但我没想到。我在类构造函数中将父向量和等级向量的大小更改为 (n+1) 并修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 2018-06-18
  • 2018-09-17
相关资源
最近更新 更多