gpt4 book ai didi

c++ - 抛出的异常 : read access violation. **node** 是 0xDDDDDDDD。发生

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:58 24 4
gpt4 key购买 nike

我必须为一个任务创建一个二叉搜索树,在我删除我的树之前一切都很好。这对我来说可能是一个非常简单的错误,但我不确定如何解决它。每次我运行程序并包含删除树的代码时,我都会收到“抛出异常:读取访问冲突。node 为 0xDDDDDDDD。已发生。”

这是我的树的代码:

Tree::Tree()
{
head = NULL;
}

Tree::~Tree()
{
deleteNodes(head);
}

string Tree::checkBalance()
{
int lh;
int rh;

lh = height(head->leftBranch);
rh = height(head->rightBranch);

if (abs(lh - rh) <= 1)
return "KEEP";
else
return "REMOVE";
}

int Tree::height(Node* node)
{
//If tree empty
if (node == NULL)
return 0;

//If not empty, find max height
return 1 + max(height(node->leftBranch), height(node->rightBranch));
}

void Tree::addNum(int num)
{
Node *newNode = new Node;
newNode->myNum = num;
newNode->leftBranch = NULL;
newNode->rightBranch = NULL;

if (head == NULL)
{
head = newNode;
}
else
{
Node *cursor = head;
bool foundSpot = false;

while (!foundSpot)
{
if (num < cursor->myNum)
{
if (cursor->leftBranch != NULL)
cursor = cursor->leftBranch;
else
{
cursor->leftBranch = newNode;
foundSpot = true;
}
}
else
{
if (cursor->rightBranch != NULL)
cursor = cursor->rightBranch;
else
{
cursor->rightBranch = newNode;
foundSpot = true;
}
}
}
}
}

void Tree::deleteNodes(Node *node)
{
if (node == NULL)
return;

//Deletes subtrees
deleteNodes(node->leftBranch);
deleteNodes(node->rightBranch);

//Deletes node
delete node;
}

任何有关导致此错误的帮助将不胜感激。当它尝试访问 deleteNodes(node->leftBranch) 时,问题代码似乎在 deleteNodes(Node *node) 中;

如果对节点代码的样子有任何疑问,请看这里:

struct Node
{
int myNum;
Node *leftBranch;
Node *rightBranch;
};

最佳答案

找到有问题的代码行。在 visual studio 中调试代码。 Tge 调试器将在检测到 cradh 时停止。您可以使用调试器生成错误发生时代码所在位置的调用堆栈。

我怀疑在这种情况下,您正在访问指向已删除内存的指针。调试堆有助于将已删除的内存设置为 0xdd。

关于c++ - 抛出的异常 : read access violation. **node** 是 0xDDDDDDDD。发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com