【问题标题】:(C++ Error: pointer being freed was not allocated) for linked lists(C++ 错误:未分配被释放的指针)用于链表
【发布时间】:2013-10-22 13:45:51
【问题描述】:

有了这个主要的:

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

这些函数定义在一个类队列中,它有一个链表,其中“头”和“尾”作为指向链表中第一个和最后一个节点的指针,每个节点都包含另一个结构“数据”,它存储一个重新定义的输入元素类型:

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 中设置断点进行调试

【问题讨论】:

  • 你遵循三法则了吗?
  • void print_first(Queue q) 更改为void print_first(Queue&amp; q)(在这两个地方),看看是否有区别。

标签: c++ pointers linked-list queue copy-constructor


【解决方案1】:

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

void print_first(Queue q)

如果你没有正确编写复制构造函数,那么函数可能会出现一些问题。

【讨论】:

    猜你喜欢
    • 2014-06-07
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多