struct Node
{
int data;
Node* next;
};
typedef Node* List_Node;
class List
{
public:
List();
~List();
void creat_List_last(); // 创建新链表
void print_List(); // 遍历输出链表
private:
List_Node head;
};
List::List()
{
head = NULL;
}
void List::creat_List_last()
{
List_Node p, q;
p = new Node;
q = p;
cout << "请输入数据(以-1表示结束):"<<endl;
cin >> p->data;
while (p->data != -1)
{
if (head == NULL)
head = p;
else
q->next = p;
q = p;
p = new Node;
cout << "请输入数据(以-1表示结束):" << endl;
cin >> p->data;
}
q->next = NULL;
delete p;
}
void List::print_List()
{
cout << "所有数据如下:" << endl;
List_Node p=head;
while (p)
{
cout<<p->data<<" ";
p = p->next;
}
}
List::~List()
{
List_Node p=head;
while (p)
{
head = p->next;
delete p;
}
}
int main()
{
List l;
l.creat_List_last();
l.print_List();
}
提示:c++ - _Block_Type_Is_Valid (pHead->nBlockUse) Error
对指针操作不是很熟悉,望博友指教
析构函数里delete p;后加上p=head;
#include <cstddef>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
typedef Node* List_Node;
class List
{
public:
List();
~List();
void creat_List_last(); // 创建新链表
void print_List(); // 遍历输出链表
private:
List_Node head;
List_Node tail;
};
List::List()
{
head = NULL;
tail = NULL;
}
void List::creat_List_last()
{
List_Node p;
int temp;
cout << "请输入数据(以-1表示结束):"<<endl;
cin >>temp;
while (temp != -1)
{
p = new Node{temp,NULL};
if (head == NULL)
{
head = p;
tail = p;
}
else
{
tail->next = p;
tail = p;
}
cout << "请输入数据(以-1表示结束):"<<endl;
cin >>temp;
}
}
void List::print_List()
{
cout << "所有数据如下:" << endl;
List_Node p=head;
while (p)
{
cout<data<<" ";
p = p->next;
}
}
List::~List()
{
List_Node p=head;
List_Node q;
while (p)
{
q = p->next;
delete p;
p = q;
}
}
int main()
{
List l;
l.creat_List_last();
l.print_List();
}
楼主,我执行你的代码获得的错误提示不一样,我获得的是 double free,大概意思是多次释放同一个资源。
主要修改了,析构函数,只有一个中间变量是没办法遍历并逐个释放资源的。参考我的析构函数。
同时,我在创建链表节点时赋予了初值防止因为初值的原因引起其他错误。
楼上正解,主要原因就是:因为你在析构时,不停的析构循环中的p。当你第一次循环释放掉 p 所指向的内存空间以后,
并没有给 p 重新赋新得内存空间,所以当执行第二次循环时,在释放 p 所指向的内存就会出错了,因为这是的 p 并没有指向任何有效空间。