损坏的指针-BST-调试
Corrupt pointer - BST - debug
我正在尝试编写简单的二进制搜索树类(BST)。
当我添加一个节点(e.value=10)时,根会得到更新,并在BST::insert(…)结束时使用VS C++调试器进行验证
然后我尝试显示(案例语句3)节点(值-10),但没有打印任何内容。原因是,当调用getRoot()时,根为NULL(?!!)
有人能帮我调试这个问题吗。
#include <iostream>
#include <stdio.h>
#include "bst_node.h"
class BST{
private:
bst_node *root;
public:
bst_node* getRoot();
void insert(bst_node *, int val);
void deleteValue(int val);
void display(bst_node *);
void destroy();
BST()
{
root = NULL;
std::cout<<"BST constructor"<<"n";
}
~BST()
{
std::cout<<"BST destructor"<<"n";
}
};
int main()
{
int item;
int choice;
BST tree1;
while(1)
{
printf("n Choices are:n");
printf("n 1.Insertbegnn 2.deleteNodenn 3.displaynn 4.exitnn");
printf(" Enter U'r choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("Enter element to be inserted: ");
scanf("%d",&item);
tree1.insert(tree1.getRoot(), item);
break;
}
case 2:
{
printf("Enter element to be deleted: ");
scanf("%d",&item);
// tree1.deleteValue(item);
break;
}
case 3:
{
tree1.display(tree1.getRoot());
break;
}
case 4:
exit(1);
break;
default: printf("INVALID CHOICE TRY AGAINn");
}
}
}
void BST::insert(bst_node* root, int val)
{
if( root == NULL)
{
// add first element
bst_node *new_node = bst_node::create_empty_node();
new_node->val = val;
root = new_node;
}
else if(val < root->val )
{
insert(root->l_child, val);
}
else if (val >= root->val)
{
insert(root->r_child, val);
}
}
void BST::display(bst_node *root)
{
if(root == NULL)
{
return;
}
else
{
std::cout << root->val <<"n";
display(root->l_child);
display(root->r_child);
}
}
void BST::deleteValue(int val)
{
std::cout<< " Do nothing";
}
bst_node* BST::getRoot()
{
return root;
}
bst_node.h
class bst_node
{
public:
int val;
bst_node *l_child;
bst_node *r_child;
static bst_node* create_empty_node();
};
bst_node* bst_node::create_empty_node()
{
bst_node *new_node;
new_node = new bst_node;
new_node -> l_child = new_node -> r_child = NULL;
return(new_node);
}
您通过将参数命名为insert()
root
来隐藏私有成员root
。对root
的所有修改都将应用于本地变量。例如:
root = new_node;
不会有任何影响。您正在为一个不再使用的vrable设置一个新值。
这样做通常是一种糟糕的做法(除了一些例外,例如setter)。尝试重命名并检查它是否至少解决了您的一些问题。
更改void BST::insert(bst_node* root, int val)
至void BST::insert(bst_node*& root, int val)
或void BST::insert(bst_node** root, int val)
在不对函数进行其他修改的情况下,最简单的方法是使用bst_node*&
指针本身只是传递给函数的一个整数,然后会复制此指针,因此在函数范围之外不会更改指针的值。对指针的引用将使您的更改在函数范围之外可用。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 在linux上调试巨大的C++项目
- 如何在BST的这个简单递归实现中消除警告
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 正在VS调试器中监视映射条目
- 使用调试/崩溃报告将应用程序部署到客户端
- VC++本机单元测试,找不到调试符号
- 如何在C++生成器中禁用"使用调试.dcus"
- 使用vscode调试时,GDB意外退出
- 即使使用调试编译标志,表达式也是"optimized out"
- 调试 CUDA MMU 故障
- 小字符串优化(调试与发布模式)
- 调试和自由执行中的信号处理
- 调试编译的服务器在数据库打开时崩溃
- Visual Studio 调试优化如何工作?
- 如何配置Visual Studio Code以使用cygwin,cmake和gcc进行调试
- 从 exe 文件 (Visual Studio ) 启动时调试断言失败
- 如何在大型c++项目的可视化代码中设置调试
- 损坏的指针-BST-调试