我目前正在測試一個鏈表,我正在構建,當我運行下面的代碼時,我得到一個「指針是免費的沒有分配」我知道這是用delete_queue功能,但我無法弄清楚。指針是免費的沒有分配
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include "smb.h"
#define BUFLEN (25)
struct Queue {
stage *front, *back;
};
typedef struct Queue * Queue;
Queue queue_create(void) {
Queue q = malloc(sizeof(struct Queue));
q->front = q->back = NULL;
return q;
}
void queue_delete(Queue q) {
stage *current, *tmp;
current = q->front;
while (current!= NULL) {
tmp = current->next;
free(current);
current = tmp;
}
free(q);
}
void queue_push(Queue q, char * name, int ncoins, int npipes) {
stage *n =malloc(sizeof(struct stage));
strcpy(n->name, name);
n->ncoins = ncoins;
n->npipes = npipes;
n->next = NULL;
stage *current;
if (q->front == NULL) {
q->front = n;
} else {
current = q->front;
while(current!= NULL){
current = current->next;
}
current = n;
}
q->back = n;
q->back->next = q->front;
}
int main(void) {
Queue q = queue_create();
queue_push(q, "courtyard", 1, 2);
int data1 = q->front->ncoins;
int data2 = q->front->npipes;
printf("%d\n", data1);
printf("%d\n", data2);
printf("%s\n", q->front->name);
queue_delete(q);
return 0;
}
我們應該假設q-> back-> next = q-> front'不是一個錯誤,而是*有意*形成一個**循環鏈表**?如果是這樣,當非空作爲終止條件不起作用時,在這樣的列表上清楚地檢查NULL。您的刪除代碼最終會刪除已刪除的節點,並且您的推送代碼將進入無限循環。 – WhozCraig