2013-10-05 3 views
0

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); 
} 

하면이 corrent 출력하지만 당신은 qu이 비어있는 경우 확인하지 않고 각각의 반복에서 qu.front()를 호출 실행 시간

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 
+0

표준 C++을 작성하려면 ''을' ' –

답변

1

로 인쇄되어 있지만. 비어있는 경우 - 그리고 마지막으로 - 코드가 손상됩니다.

가장 간단한 해결책은 qu가 비어 있는지 확인하는 것입니다 :

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

그러나, 이상한 보인다. 루프를 완전히 변경하고 while 루프의 조건으로 !qu.empty()을 사용합니다.

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); 
} 
+0

으로 대체하십시오. 이미 설명 해 주셔서 감사합니다. :) –

1

은 무슨 일이 트리의 마지막 "잎"에 도착하면, temp->lefttemp->right 모두 NULL 있다는 것입니다 그리고 당신은 빈 한때 목록을 가져. qu.front()을 호출하면 빈 목록에서 정의되지 않은 동작이 발생합니다. http://en.cppreference.com/w/cpp/container/list/front

앞에 전화하기 전에 크기 확인을 추가 할 수 있습니다.

관련 문제