神秘的分割断层破坏

Mysterious Segmentation Fault on Destruction

本文关键字:分割      更新时间:2023-10-16

在歌曲"上帝写在LISP代码中"中,他们用C(或C++)说"只有上帝才能造树";我开始相信了。

我有一个树类的开始,但我的类在销毁时出现段错误,说错误是我的队列free_spaces,尽管我不明白为什么。此外,随机错误似乎潜伏在这里和那里。

我以前从未使用过这样的模板,所以也许那里有一些隐藏的滥用。

任何帮助将不胜感激。

标题.h

#include<vector>
#include<queue>
#include<iostream>
using namespace std;
template <class T>
class node {
    public:
        int leftChild,parent;
        bool empty;
        T data;
        node() : leftChild(-1), parent(-1), empty(true) {}
};
template <class T>
class AvlTree {
    private:
        vector< node<T> > nodes;
        queue<int> free_spaces;
        int root;
        int newnode(int parent){
            int index=nodes.size();
            nodes.push_back(node<T>());
            nodes[index].parent=parent;
            return index;
        }
    public:
        AvlTree(){
            nodes.push_back(node<T>());
            root=0;
        }
        void grow(){
            nodes[root].leftChild=newnode(root);
        }
};

主H

#include "header.h"
int main(){
    AvlTree<int> bob;
    bob.grow();
    cerr<<"Made it to end."<<endl;
}

问题出在以下代码行中:

nodes[parent].leftChild=newnode(parent);

只需将其替换为此即可修复它:

int left = newnode(parent);
nodes[parent].left = left;

这最终归结为评估的顺序。问题是newnode()函数修改了向量长度。这样做可能会迫使std::vector<>重新分配内存以使其增长(即,如果当前容量不足)。如果遇到这种情况,左侧nodes[parent].left表达式(如果在newnode()调用之前计算)将指向可能无效的内存位置。

Valgrind 显示此错误:

==23995== Invalid write of size 4
==23995==    at 0x400F68: AvlTree<int>::grow() (/tmp/header.h:39)
==23995==    by 0x400BC6: main (/tmp/t.cc:5)
==23995==  Address 0x5967770 is 0 bytes inside a block of size 16 free'd
==23995==    at 0x4C29DFD: operator delete(void*) (/coregrind/m_replacemalloc/vg_replace_malloc.c:456)
==23995==    by 0x401FC5: __gnu_cxx::new_allocator<node<int> >::deallocate(node<int>*, unsigned long) (/usr/include/c++/4.4/ext/new_allocator.h:95)
==23995==    by 0x40187B: std::_Vector_base<node<int>, std::allocator<node<int> > >::_M_deallocate(node<int>*, unsigned long) (/usr/include/c++/4.4/bits/stl_vector.h:146)
==23995==    by 0x401743: std::vector<node<int>, std::allocator<node<int> > >::_M_insert_aux(__gnu_cxx::__normal_iterator<node<int>*, std::vector<node<int>, std::allocator<node<int> > > >, node<int> const&) (/usr/include/c++/4.4/bits/vector.tcc:361)
==23995==    by 0x40106B: std::vector<node<int>, std::allocator<node<int> > >::push_back(node<int> const&) (/usr/include/c++/4.4/bits/stl_vector.h:741)
==23995==    by 0x40131A: AvlTree<int>::newnode(int) (/tmp/header.h:24)
==23995==    by 0x400F67: AvlTree<int>::grow() (/tmp/header.h:39)
==23995==    by 0x400BC6: main (/tmp/t.cc:5)

这应该足以让您找到错误。