2012-10-01 35 views
1

我正在处理双链表,并且我的pop()函数遇到了问题。C:双链表中的弹出功能

//QueueElement describe the block in the cache 
typedef struct _queue_ele_ 
{ 
    char *content; //the data of the block 
    struct _queue_ele_ *prev; 
    struct _queue_ele_ *next; 
}QueueElement; 

typedef struct _queue_ 
{ 
    int queue_len; 
    int max_queue_size; 
    QueueElement *head; 
    QueueElement *tail; 
}MyQueue; 

弹出功能工作,直到有2个要素的输入(I由坡平逐个和释放内存清除队列)

弹出:

// head is removed and returned 
QueueElement* pop(MyQueue* myqueue) 
{ 
    // if empty 
    if(myqueue->queue_len == 0) return NULL; 

    QueueElement *p = myqueue->head; 

    // if one element 
    if(myqueue->queue_len == 1) 
    { 
     myqueue->queue_len--; 
     myqueue->head = NULL; 
     myqueue->tail = NULL; 

     return p; 
    } 
    else 
    { 
     myqueue->queue_len--; 

     //remove the head from the queue 
     myqueue->head = myqueue->head->prev; 
     myqueue->head->next = NULL; //******************Seg Fault here 

     p->prev = NULL; 

     return p; 
     } 
} 

错误我在有两个元素时得到的是显示的行中的分段错误,但是它对更多的队列起作用。为什么不让它让NULL分配给myqueue-> head-> next ???

回答

4

更改此:

myqueue->head = myqueue->head->prev; 
myqueue->head->next = NULL; //******************Seg Fault here 

要:

myqueue->head = myqueue->head->prev; 
if (myqueue->head != NULL) { 
    myqueue->head->next = NULL; 
} 

很可能是你正在尝试取消引用一个NULL指针。它也会出现,你可能没有从你正在删除的节点上免费调用内存泄漏,但它可能会在代码中的其他地方执行。

+0

它工作!谢谢! – spatara

+2

很高兴听到它。您可能希望将此标记为“已接受的答案”,以便其他人知道您解决了问题。快乐的编码! – bohney