2013-03-26 1 views
3

기본적으로 연결된 목록을 사용하여 대기열에있는 사람들을 시뮬레이션하고 대기열 앞에있는 사람이 업무를 마칠 때까지 기다립니다. . 처음 몇 사람들은 잘 지내지 만, 두 번째 대기열 해제 호출을 받으면 나를 세그 폴트합니다. gdb 디버거는 오류가이 줄에서 오는 것이라고 말합니다. head = current-> next; (여기서 current = head). (난 메모리 누수가 발생하고있어가 대기 상태 때 경우에) 여기 dequeue 함수를 사용하는 SegFaulting

void BankQueue::dequeue() 
    { 
     Node* current=head; 
     head=current->next; 
     if(head!=NULL) 
     { 
      head->prev=NULL; 
     } 
     delete current; 
    } 

가 대기열 기능입니다 : 여기

내 디큐 기능입니다

void BankQueue::enqueue(Customer s) 
    { 
     Node* node= new node; 
     node->data=s; 
     node->next=NULL; 
     if(tail==NULL) 
     { 
       head=node; 
       tail=node; 
       node->prev=NULL; 
     } 
     else 
     { 
       node->prev=tail; 
       tail->next=node;; 
       tail=node; 
     } 

너희들로 제공 할 수있는 어떤 도움 segfault가 일어날 수있는 곳까지는 놀라운 일이 될 것입니다. 미리 감사드립니다.

필요한 경우 자세한 정보를 제공 할 수 있습니다.

+0

우연히'Node'에 대한 소멸자에서 우스운 일을하고 있습니까? 내가 본 유일한 사실은'dequeue' 함수 ('head = current-> next;')에서'head' ('current'')가'NULL'인지를 체크하지 않는다는 것입니다. 비어있는 큐에서 큐를 해제하는 경우이 작업이 중단됩니다. ** 편집 : ** 아, 그게 문제라고 생각합니다.'dequeue'는'enqueue '에 의해 사용 된'tail' 포인터를 재설정하지 않기 때문입니다. – paddy

답변

1

dequeue 기능에 결함이 있습니다. headNULL 될 것 인 경우에 발생하는 봐 :

void BankQueue::dequeue() 
{ 
    // current == NULL 
    Node* current = head; 
    // Setting head to NULL->next 
    // This will reference memory location 0x00000000 + (some offset) 
    head=current->next; 
    // This is undefined, but it most likely will return true 
    if(head!=NULL) 
    { 
     // undefined 
     head->prev=NULL; 
    } 
    // Delete NULL 
    delete current; 
} 

는 또한, 그래, tail 너무 거기에 업데이트해야합니다.

// After you've made sure that head is valid 
if (head == tail) { 
    // there is only node, so we just clear tail 
    tail = NULL; 
} 
// Then you proceed with removal 

토마스, 당신의 의견에 대한 응답 :

void BankQueue::dequeue() 
{ 
    // If the queue has instances 
    if (head) 
    { 
     // If there is only one instance 
     if (head == tail) 
     { 
      tail = NULL; 
     } 

     // set the new head 
     head = head->next; 
     // delete the old head if it exists 
     if (head->prev) 
     { 
      delete head->prev; 
     } 
     // null data 
     head->prev = NULL; 
    } 
} 
+0

그래서 if (머리 == 꼬리)를 배치하고 싶습니다 어디서? 또한, 내가 머리를 배치 할 필요가 = 현재 -> 다음 if (head! = NULL) 안에? – Thomas

+0

나는 당신을 위해 채운 기능으로 나의 대답을 편집했다. –

+0

끝내 주셔서 감사합니다. – Thomas

0

내가 코멘트를했지만, 나는이 가능성이 가장 높은 문제라고 생각하기 때문에 확장 것이다.

dequeue 함수는 tail 포인터를 재설정하지 않습니다. enqueue 함수는이 값을 사용하여 큐가 비 었는지 확인하기 때문에 큐를 비우고 다시 항목을 넣으면 문제가 발생합니다 (head이 NULL이기 때문에).

+0

어떻게 테일 포인터를 재설정하겠습니까? – Thomas

+0

네가 dequeue하고 새로운'head'가'NULL'이라는 것을 알게되면'tail'을'NULL'으로 설정해야합니다. 머리가 없다면 꼬리도 없기 때문에 이것은 당신에게 의미가 있어야합니다. – paddy

0

에서 dequeue 조건을 넣으면 if (! head) return; 첫 번째 줄로 제안 된대로 그 후에 설정됩니다.

관련 문제