EXC_BAD_ACCESS (EXC_i386_GPFLT) 在BST中插入节点时
EXC_BAD_ACCESS (EXC_i386_GPFLT) when inserting node in BST
我正在尝试通过 C++ 从 XCode 中的给定数组填充二叉搜索树。
我正在使用递归以下列方式生成 BST。
int main(int argc, const char * argv[]) {
const int length = 19;
int data[length] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20};
Node* root = new Node(12);
for(int i = 0;i<length;i++){
insert(data[i], &root);
}
return 0;
}
这是我的插入函数
void insert(int key, Node **current)
{
if(*current == NULL)
{
Node *newnode = new Node(key);
*current = newnode;
}
else
{
if(key < (*current)->value) ---------EXCEPTION HERE
insert(key, &(*current)->left);
else
insert(key, &(*current)->right);
}
}
有时会抛出异常EXC_BAD_ACCESS(代码=EXC_i386_GPFLT)。
相同的逻辑在 Visual Studio 和 C# 中运行良好。
我在 C++ 中对内存做错了什么吗?
我不太熟悉 C++,但似乎一切都应该有效。
在应用夏洛克·福尔摩斯的方法来寻找漏洞后(1),最可能的解释是 left
和 right
class 成员没有被显式初始化为 nullptr
.
(1) "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth."
我正在尝试通过 C++ 从 XCode 中的给定数组填充二叉搜索树。 我正在使用递归以下列方式生成 BST。
int main(int argc, const char * argv[]) {
const int length = 19;
int data[length] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20};
Node* root = new Node(12);
for(int i = 0;i<length;i++){
insert(data[i], &root);
}
return 0;
}
这是我的插入函数
void insert(int key, Node **current)
{
if(*current == NULL)
{
Node *newnode = new Node(key);
*current = newnode;
}
else
{
if(key < (*current)->value) ---------EXCEPTION HERE
insert(key, &(*current)->left);
else
insert(key, &(*current)->right);
}
}
有时会抛出异常EXC_BAD_ACCESS(代码=EXC_i386_GPFLT)。 相同的逻辑在 Visual Studio 和 C# 中运行良好。 我在 C++ 中对内存做错了什么吗? 我不太熟悉 C++,但似乎一切都应该有效。
在应用夏洛克·福尔摩斯的方法来寻找漏洞后(1),最可能的解释是 left
和 right
class 成员没有被显式初始化为 nullptr
.
(1) "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth."