如何从链表中出列时释放内存?

时间:2018-02-04 22:55:20

标签: c queue malloc

我正在使用malloc()函数来在C中创建一个队列,问题是当我使用dequeue()函数时,我会留下一个未引用的元素。我必须每秒多次使用这个函数,所以我想知道哪个是处理它的最佳方法,或者是否有比使用malloc()更好的方法。这是两个功能:

void enqueue(struct Queue *q, char c){
//adds an element to the queue
    struct Member* m = malloc(sizeof *m);//in order to make m global    
    if(!m){ perror("malloc");exit(EXIT_FAILURE);}
    if(q->length == 0){

        m->ch = c;
        q->first = m;
        q->last = m;

    }else{    
        m->ch = c;
        q->last->next = m;
        q->last = m;
    }   
    q->length++;
}

char dequeue(struct Queue *q){
//returns the first element of the queue an delete it
    char c;
    if(q->length >0){
        q->length--;
        c = q->first->ch;
        q->first= q->first->next;
        //CLEAR THE UNREFERENCED VARIABLE
    }
    return c;
}

谢谢!

修改

这些是我正在使用的结构:

typedef struct Queue{
      int length;
      struct Member *first;
      struct Member *last;
}Queue;

typedef struct Member{
      char ch;
      struct Member *next;
}Member;

1 个答案:

答案 0 :(得分:1)

首先将unreferenced variable存储到temporary variable,以便在更改队列的第一个节点后free {/ 1}}。

//returns the first element of the queue and delete it
char dequeue(struct Queue *q){

    struct Member* temp = q->first;;
    char c;

    if(q->length >0){
        q->length--;
        c = q->first->ch;
        q->first= q->first->next;
        free(temp);
    }
    return c;
}

您可以查看有关free here

的更多信息