下面的程序是一棵bst树,在未优化的设置下可以正常工作,但是在特殊情况下会生成SIGSEGV。由于我的调试技能并没有扩展到汇编语言,因此我可以使用一些输入来导致此错误。下面是完整的代码,因此可以将其复制。没什么特别的,这里有一个保存节点数据的节点结构,一个简单的插入操作以及一种确认树高的方法。
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct avl_tree_node //node data
{
int data;
int balance{0};
avl_tree_node *left{NULL};
avl_tree_node *right{NULL};
avl_tree_node *parent{NULL};
}node;
class avl
{
private:
node *root;
int get_height(node *head) //calculates the height
{
if (head == NULL)
return -1;
int l_height = get_height(head->left);
int r_height = get_height(head->right);
if (l_height > r_height)
return l_height+1;
return r_height+1;
}
void unbalanced_insert(node *head, int item); //method definition for a simple insert
public:
avl(int data)
{
root->data = data;
root->parent = NULL;
root->left = NULL;
root->right = NULL;
}
int height() //gives the height
{
return get_height(root);
}
void unbalanced_insert(int item) //wrapper
{
unbalanced_insert(root, item);
}
};
void avl::unbalanced_insert(node *head, int item) //inserts node to the tree
{
//cout << "stepped" << endl;
if (item > head->data)
{
if (head->right == NULL)
{
head->right = (node*)malloc(sizeof(node));
head->right->data = item;
head->right->parent = head;
head->right->left = NULL;
head->right->right = NULL;
head->balance = 1;
return;
}
unbalanced_insert(head->right, item);
head->balance++;
return;
}
else
{
if (head->left == NULL)
{
head->left = (node*)malloc(sizeof(node));
head->left->data = item;
head->left->parent= head;
head->left->left = NULL;
head->left->right = NULL;
head->balance = -1;
return;
}
unbalanced_insert(head->left, item);
head->balance--;
return;
}
}
int main()
{
avl a(0);
for (int i = 1; i < 5; i++) //works until i < 4
{
a.unbalanced_insert(i);
}
cout << a.height() << endl;
return 0;
}
在正常情况下,我很乐意此选项可以与未优化的标志一起使用,但是我必须使用特定的标志来构建它。其中之一是-O2
标志。分段错误发生在avl a(0)
对象构造和main内部的for循环之间。该错误似乎也取决于for循环的布尔检查。如果i < 4
并用以下命令执行,则可以正常工作:g++ avl.cpp -g -O2 -o program && ./program
一个明显的问题,它发生在main
中的第一个函数调用上,即avl a(0)
:
root->data = data;
root
未初始化,因此行为未定义。