我正在测试我正在构建的链接列表,当我运行下面的代码时,我得到一个“指针是免费的未分配”我知道这与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;
}
答案 0 :(得分:0)
试试这个
while(current->next!=NULL)
而不是
while(current!=NULL)
当你到达最后一个节点时,你正在调用tmp-&gt; next,它超过了最后一个节点。所以你的指针指向不知名的地方。