(C++ 错误:未分配正在释放的指针)为链表

(C++ Error: pointer being freed was not allocated) for linked lists

本文关键字:释放 指针 链表 错误 C++ 分配      更新时间:2023-10-16

有了这个主:

void print_first(Queue q);
int main()
{
   Queue q1;
   Queue q2(4);
   q2.push(5);
   q2.push(3);
//   q2.print_list();
   for (int i = 0; i < 3; i++)
   {
      print_first(q2);
   }
   return 0;
}
void print_first(Queue q)
{
   if (!q.isEmpty())
   {
      cout << q.pop() << endl;
   }
   else
   {
       cout << "Nothing in queue" << endl;
   }
}

以及类队列中的这些函数定义,该类队列具有链表,其中"头"和"尾"作为指向链表中第一个和最后一个节点的指针,每个节点都包含另一个结构"data",该结构存储一个重新定义的类型ElementType:

bool Queue::push(ElementType newElement)
{
   tail->next = new Node;
   if (tail->next == NULL)
   {
      return false;
   }
   tail->next->data.value = newElement;
   tail->next->next = NULL;
   tail = tail->next;
   return true;
}
ElementType Queue::pop()
{
   Node *newNode;
   ElementType returnData;
   returnData = head->data.value;
   newNode = head;
   head = head->next;
   delete newNode;
   return returnData;
}
bool Queue::isEmpty()
{
   if(head == NULL)
   {
       return true;
   }
   return false;
}

为什么我会收到此错误?4装配线模拟器(9701) malloc: * 对象 0x1001000e0 的错误:未分配正在释放的指针* 在malloc_error_break中设置断点进行调试

有了您展示的代码,我认为问题是您将队列的副本q传递给函数print_first

void print_first(Queue q)

如果您没有正确编写复制构造函数,那么该函数可能会遇到一些问题。