gpt4 book ai didi

c++ - [错误]未分配正在释放的指针

转载 作者:行者123 更新时间:2023-11-28 03:08:05 26 4
gpt4 key购买 nike

我正在使用 C++ 中的 STL 练习树的 BFS 代码,我遇到了一个无法调试的运行时错误。如果我不调用 printout() 函数,一切正常。请帮忙,因为我是 STL 的新手..

#include<iostream>
#include<malloc.h> //on llvm we don't need this
#include<list>
using namespace std;
typedef struct Node{
int val;
struct Node* left;
struct Node* right;
}node;
void push(node** root,int val)
{
if(!(*root))
{
node* temp=(node*)malloc(sizeof(node));
temp->val=val;
temp->right=temp->left=NULL;
*root=temp;
}
else if(val<(*root)->val)
push(&((*root)->left),val);
else
push(&((*root)->right),val);
}

void printout(node* head)
{
node* temp;
temp=head;
list<node*>qu;

//using bfs here
while(temp!=NULL)
{
cout<<temp->val<<endl;
if(temp->left!=NULL)
qu.push_back(temp->left);
if(temp->right!=NULL)
qu.push_back(temp->right);
temp=qu.front();
qu.pop_front();
//free(temp);
}
}

int main()
{
node* root=NULL;
push(&root,3);
push(&root,4);
push(&root,1);
push(&root,10);
push(&root,2);
printout(root);
}

虽然它正在打印正确的输出但是有运行时间

3
1
4
2
10
a.out(613) malloc: *** error for object 0x7fff55ed8bc8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

最佳答案

您在每次迭代中调用 qu.front() 而不检查 qu 是否为空。如果它是空的——最终它将是——你的代码就会中断。

最简单的解决方案是检查 qu 是否为空:

if (qu.empty()) {
temp = NULL;
} else {
temp=qu.front();
qu.pop_front();
//free(temp);
}

但是,这看起来很奇怪。我会完全改变循环并使用 !qu.empty() 作为 while 循环的条件。

list<node*> qu;
qu.push_back(head);
while(!qu.empty()) {
node* temp = qu.front();
qu.pop_front();
if(temp->left)
qu.push_back(temp->left);
if(temp->right)
qu.push_back(temp->right);
//free(temp);
}

关于c++ - [错误]未分配正在释放的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195540/

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