2017-03-25 4 views
0

프로그램이 실행되고 테스트가 성공하지만 목록과 테스트 결과 사이에 다음이 표시됩니다. 할당 _2.2 (10729,0x7fff78db0300) malloc : * 개체 0x7fb132d00000에 대한 오류 : 포인터 해방 중임이 할당되지 않았습니다. *은 디버그를 위해 malloc_error_break에 중단 점을 설정합니다. 어떻게 해결할 수 있습니까?순환 링크 된 목록의 메모리 오류

MAIN.CPP

#include "OLinkedList.h" 

using namespace std; 

int main(int argc, char** argv) { 
    OLinkedList CircleList; 
    CircleList.fillList(0); 
    CircleList.prntList(); 
    CircleList.OTest(); 
    return 0; 
} 

OLinkedList.h

#ifndef OLINKEDLIST_H 
#define OLINKEDLIST_H 

#include <iostream> 
#include <iomanip> 
using namespace std; 

class OLinkedList{ 
private: struct Link{ 
       int data; 
       Link *next; 
      }; 
      Link *head; 
      Link *tail; 
public:  OLinkedList(){head = nullptr; tail = nullptr;}; 
      ~OLinkedList(); 
     void fillList(int); 
     void prntList(); 
     void OTest(); 

}; 

//Destructor for Class used to delete memory of list 
OLinkedList::~OLinkedList(){ 
    Link *linkPtr = head; 
    Link *nextPtr; 

    //traverses to the end of the list to delete memory 
    do 
    { 
     nextPtr = linkPtr->next; 
     delete linkPtr; 
     linkPtr = nextPtr; 
    }while(linkPtr!= nullptr); 
} 

// 
void OLinkedList::fillList(int size){  
    Link *front = new Link; //create first link 
    head = front; //set first link = to traversal 
    head->data = size++;   //Fill the front with data 
    head->next = nullptr;  //Point the front to no where 

    Link *temp = head;  
    do{ 
     Link *end = new Link; //Create a new link 
     end->data = size++;  //Fill with data 
     end->next = nullptr;  //Point to no where 
     temp->next=end;//Previous link will point to the end 
     temp=end; //Now this has become previous link 
     tail = end; 
     tail->next = head; 
    }while(size < 10);   //Repeat until filled 

} 

void OLinkedList::prntList(){ 
    Link *linkPtr; 

    linkPtr = head; 
    int i = 0; 
    do{ 
     cout<<" "<<setprecision(3)<<linkPtr->data; 
     linkPtr = linkPtr->next; 
     i++; 
    }while(i < 10); 
} 

//Used to prove list is circular 
void OLinkedList::OTest(){ 
    Link *linkPtr = tail->next; 
    cout<<"\nAfter "<<tail->data<<" is "<<linkPtr->data; 
} 
#endif /* OLINKEDLIST_H */ 

답변

0

설정할 때 tail-> 머리 옆에, 당신이를 만드는 순환 링크 된 목록 예정된. Do while 루프는 nullptr 대신 linkPtr! = head를 확인해야합니다. 머리를 두 번 자유롭게 사용하고 있기 때문입니다. 이는 포인터를 삭제해도 이전에 포인터를 가리키는 변수가 무효화되지 않으므로 루프가 결국 머리로 돌아 오기 때문입니다.

사실, 이중 자유가 아닌 경우 코드가 무한 루프가됩니다.