gpt4 book ai didi

c++ 创建新的 LinkedList 类 : Clear() method pointer being freed not allocated

转载 作者:行者123 更新时间:2023-11-28 03:01:05 32 4
gpt4 key购买 nike

我试图创建一个新的链表类。代码运行良好,但仍然有一些错误消息。

我知道问题位于 LinkedList::Clear();方法。

我提出了 2 个建议

P"用于定位和删除(delete p;),

和“savecurrent”定位下一步删除的位置;

这里是错误信息

HelloWorld(25850,0x7fff72537310) malloc: *** error for object 0x100b01030: 
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
The program has unexpectedly finished.

代码如下

#include "linkedlist.h"
#include "strlib.h"
#include <string>


LinkedList::LinkedList(){
x_front = NULL;
x_size =0;
}

LinkedList::~LinkedList() {
ListNode*p = x_front;
ListNode*savecurrent = x_front;
for(p ; p != NULL ; p = savecurrent){
savecurrent = savecurrent->next;
delete p;
}
}



void LinkedList::add(int value){
if(x_front == NULL){
x_front = new ListNode(value,NULL);
}
else {
ListNode *current = x_front;
while(current-> next != NULL){
current = current -> next;
}
current->next = new ListNode(value,NULL);
}
x_size++;
}


void LinkedList::clear(){
ListNode*p = x_front;
ListNode*savecurrent = x_front;
for(p ; p != NULL ; p = savecurrent){
savecurrent = savecurrent->next;
delete p;
x_size --;
}
}

string LinkedList::toString() const{
string mystring;
for(ListNode*p=x_front;p!=NULL;p=p->next){
mystring = mystring + " " + integerToString(p->value);
}
return mystring;
}


int LinkedList::size() const{
return x_size;
}

标题.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <iostream>
#include <string>
using namespace std;

struct ListNode{
int value;
ListNode* next;

ListNode(int d,ListNode *n){
value = d;
next = n;
}
};

class LinkedList
{
public :
LinkedList();
~LinkedList();
void add(int value);
void clear();
int get(int index) const;
bool isEmpty() const;
void remove(int index);
int size() const;
string toString() const;

private :
ListNode* x_front;
int x_size;
};

#endif // LINKEDLIST_H

最佳答案

您正在分配单个对象(例如,new ListNode(value,NULL)),但您正在删除数组对象,例如,delete[] p。分配的形式必须与解除分配的形式完全相同。尝试从 delete 表达式中删除 []

关于c++ 创建新的 LinkedList 类 : Clear() method pointer being freed not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833125/

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