简体   繁体   中英

Pointer being free was not allocated

I'm currently testing a linked list that I'm building and when I run the code below I get a "pointer being free was not allocated" I know that this is to do with the delete_queue function but I can't figure it out.

#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;
}

try this

 while(current->next!=NULL)

as opposed to this

 while(current!=NULL)

when you get to the last node you are calling tmp->next which is past the last node. so your pointer is pointing to the middle of nowhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM