簡體   English   中英

空閑指針未分配

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM