gpt4 book ai didi

c++ - (C++ 错误 : pointer being freed was not allocated) for linked lists

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:49 32 4
gpt4 key购买 nike

主要是:

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

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

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)

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

关于c++ - (C++ 错误 : pointer being freed was not allocated) for linked lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19369636/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com