【问题标题】:[Error]pointer being freed was not allocated[错误]被释放的指针未分配
【发布时间】:2013-10-12 07:07:42
【问题描述】:

我正在用 C++ 中的 STL 练习树的 BFS 代码,我遇到了一个无法调试的运行时错误。如果我不调用 printout() function,一切正常。 请帮忙,因为我是 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

【问题讨论】:

  • 如果你想写标准的C++,把&lt;malloc.h&gt;换成&lt;cstdlib&gt;

标签: c++ gcc stl malloc llvm


【解决方案1】:

您在每次迭代中调用 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);
}

【讨论】:

    【解决方案2】:

    当你到达树中的最后一个“叶子”时,temp-&gt;lefttemp-&gt;right 都是NULL,你会得到一个空的 qu 列表。 调用 qu.front() 会导致空列表出现未定义行为:http://en.cppreference.com/w/cpp/container/list/front

    您可以在调用 front 之前添加尺寸检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多