我有一个包含指针next
的结构。我试图建立一个结构队列,但是当我调用enqueue/dequeue
时,我最终会在尝试写信息时遇到错误;并且不知道它是否归因于enque/dequeue/insert
。只是学习C并且不确定free/malloc
或者是否有必要。 Insert基于int值(最小值优先)。
struct queue {
struct RCB* front;
struct RCB* back;
};
/*Initialize queue */
struct queue* new_queue(void){
struct queue* tmp = malloc( 1 * sizeof(tmp));
tmp->front = NULL;
tmp->back = NULL;
return tmp;
}
/*Add RCB to Queue FIFO */
struct queue* enqueue(struct queue* queue, struct RCB* rcb){
if(queue->front == NULL && queue->back == NULL){
queue->front = rcb;
queue->back = rcb;
printf("added front to queue\n");
return queue;
}
else {
queue->back->next = rcb;
queue->back = rcb;
printf("added to queue\n");
}
return queue;
}
/*Remove RCB from Queue FIFO */
struct RCB* dequeue(struct queue* queue){
struct RCB *tmp1 = (struct RCB *)malloc(sizeof(struct RCB));
struct RCB *tmp2 = (struct RCB *)malloc(sizeof(struct RCB));
if(queue->front == NULL && queue->back == NULL){
printf("queue is empty\n");
}
tmp1 = queue->front;
tmp2 = tmp1->next;
queue->front = tmp2;
if(queue->front == NULL){
queue->back = queue->front;
printf("removed rcb from queue\n");
}
return tmp1;
}
/*Insert RCB into Queue */
struct queue* insert(struct queue* queue, struct RCB* rcb){
if(queue->front == NULL && queue->back == NULL){
queue->front = rcb;
queue->back = rcb;
return queue;
}
if(queue->front->next == NULL){
queue->front->next = rcb;
return queue;
}
struct RCB *tmp = (struct RCB *)malloc(sizeof(struct RCB));
tmp = queue->front;
while(tmp->next->b2r < rcb->b2r || tmp->next == NULL){
tmp = tmp->next;
}
rcb->next = tmp->next;
tmp->next = rcb;
return queue;
}
非常感谢任何帮助。
答案 0 :(得分:3)
new_queue
中,struct queue* tmp = malloc( 1 * sizeof(tmp));
是错误的,因为这会分配一个指针大小为struct queue
的缓冲区,而不是struct queue
的大小,也是1*foo
事情根本没用。使用以下:
struct queue* tmp = malloc(sizeof(*tmp));
在dequeue
中,您正在分配两个struct RCB
的缓冲区,同时通过分配指针tmp1 and tmp1
暂时丢失对它们的引用,这些不是必需的,而您是造成内存泄漏。你需要的只是两个指针:
struct RCB* dequeue(struct queue* queue) {
struct RCB *tmp1;
struct RCB *tmp2;
if(queue->front == NULL && queue->back == NULL) {
printf("queue is empty\n");
}
tmp1 = queue->front;
tmp2 = tmp1->next;
queue->front = tmp2;
if(queue->front == NULL) {
queue->back = queue->front;
printf("removed rcb from queue\n");
}
return tmp1;
}