C++二叉搜索树会产生分段错误

C++ binary search tree creates segmentation fault

本文关键字:分段 错误 搜索树 C++      更新时间:2023-10-16

我正在尝试制作一个通过操作码识别 AVR 汇编指令的程序,因为这些只是 1 和 0 的列表,我认为这将是一个很好的项目来制作二叉搜索树。

可悲的是,在尝试搜索树时,我不断遇到分段错误。据我了解,seg 错误通常是尝试使用不指向任何内容的指针执行操作的结果,但由于我有一个布尔值,我首先检查它不应该发生。

我很确定这与我使用指针的方式有关,因为我对这些不是很有经验。但我似乎无法弄清楚出了什么问题。

下面是涉及的代码(SearchTree在这个最小示例中只是一个全局变量,而不是在实际程序中。

代码:

#include <iostream>
void ADD(short &code) {std::cout << code << "n";}
void LDI(short &code) {std::cout << code << "n";}
void SBRC(short &code){std::cout << code << "n";}
struct node
{
void(* instruct)(short &code);
bool hasInst = false;
struct node *zero;
bool hasZero = false;
struct node *one;
bool hasOne = false;
};
node SearchTree;
auto parseOpcode(short code, node *currentRoot)
{
std::cout << "Looking for a:  " << ((code >> 15) & 0b01 == 1) << std::endl;
std::cout << "Current node 1: " << (*currentRoot).hasOne << std::endl;
std::cout << "Current node 0: " << (*currentRoot).hasZero << std::endl;
// Return instruction if we've found it.
if ((*currentRoot).hasInst) return (*currentRoot).instruct;
// Case current bit == 1.
else if ((code >> 15) & 0b01 == 1)
{
if ((*currentRoot).hasOne) return parseOpcode((code << 1), (*currentRoot).one);
else throw "this instruction does not exist";
}
// Case current bit == 0.
else {
if ((*currentRoot).hasZero) return parseOpcode((code << 1), (*currentRoot).zero);
else throw "this instruction does not exist";
}
}
void addopcode(void(& instruct)(short &code), int opcode, int codeLength)
{
node *latest;
latest = &SearchTree;
for (int i = 0; i <= codeLength; i++)
{
// Add function pointer to struct if we hit the bottom.
if (i == codeLength)
{
if ((*latest).hasInst == false)
{
(*latest).instruct = &instruct;
(*latest).hasInst = true;
}
}
// Case 1
else if (opcode >> (codeLength - 1 - i) & 0b01)
{
if ((*latest).hasOne)
{
latest = (*latest).one;
}
else{
node newNode;
(*latest).one = &newNode;
(*latest).hasOne = true;
latest = &newNode;
}
}
// Case 0
else {
if ((*latest).hasZero)
{
latest = (*latest).zero;
}
else{
node newNode;
(*latest).zero = &newNode;
(*latest).hasZero = true;
latest = &newNode;
}
}
}
}

int main()
{
addopcode(ADD, 0b000011, 6);
addopcode(LDI, 0b1110, 4);
addopcode(SBRC, 0b1111110, 7);
short firstOpcode = 0b1110000000010011;
void(* instruction)(short &code) = parseOpcode(firstOpcode, &SearchTree);
instruction(firstOpcode);
return 0;
}

编辑:我的文件顶部仍然有一些 #includes 链接到我没有放在StackOverflow上的代码。

发生错误是因为我忘记使用new关键字,因此用局部变量填充我的搜索树(当我开始搜索树时,这些变量现在显然更长了(。

使用以下方法修复:

node *newNode = new node();
(*latest).one = newNode;
(*latest).hasOne = true;
latest = newNode;

而不是:

node newNode;
(*latest).one = &newNode;
(*latest).hasOne = true;
latest = &newNode;