c++ - g++ -O2 标志给出分段错误
问题描述
下面的程序是一个 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
初始化,因此行为未定义。
推荐阅读
- javascript - 使用 Sublime 重新缩进缩小的 Javascript
- linux - 为 SIGSEGV 注册信号处理程序并且仍然能够从操作系统创建完整的故障转储
- python - 在情节中自定义带有和不带标签的刻度
- java - atlassian jira 密码编码
- php - laravel 命令 php artisan make:model 运行命令文件夹中的所有命令
- reactjs - 在 Typescript 中的另一个 thunk 函数中执行 thunk 函数
- azure-devops - 如何从另一个项目中的另一个管道启动 Azure 管道?
- laravel - Laravel 升级到版本 8 抛出错误
- excel - 从超过 10 列的多列 ListBox 中的工作表的第一行填充标题文本
- spring-boot - 如何模拟存储库,使其不插入或从数据库中提取数据