神秘的分割断层破坏
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)
这应该足以让您找到错误。
相关文章:
- 如何在C++中从字符串中分割字符
- C++映射分割错误(核心转储)
- C++为线程工作动态地分割例程
- 由cin中的字符串中未捕获空白引起的分割错误
- 删除映射和分割错误中的一个过去结束元素
- 在指向函数中读取变量时出现分割错误
- 在链表中的第 n 位插入显示分割错误
- 较高值 n 的分割错误(例如 n=999997)
- 是否可以制作没有内部分割的cgal 3d多多马因网格?
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 分割错误:向量中的擦除功能
- 向量向量的分割错误
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 集合布局上的 Qt 分割错误
- 高达20亿的筛子会产生分割错误
- 对向量使用推回函数时的分割错误
- 如何在使用OpenCV C++应用K均值后提取分割图像