![](/img/trans.png)
[英]Should the pointer being passed to free() point to the start of the allocated space?
[英]Pointer being free was not allocated
我目前正在测试正在构建的链表,当我在下面的代码中运行时,我得到“没有分配空闲的指针”,我知道这与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;
}
尝试这个
while(current->next!=NULL)
与此相对
while(current!=NULL)
当您到达最后一个节点时,您正在调用tmp-> next,该节点在最后一个节点之后。 所以您的指针指向虚无的中心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.