I’m just creating a simple list and then destroying it. And something is going wrong and I always get this annoying error message:
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
Here’s the code:
#include<iostream>
#include<Windows.h>
using namespace std;
struct node
{
int data;
node *next;
};
class list
{
protected:
node *top;
public:
list()
{
top=NULL;
}
list random()
{
int x=rand()%10;
for(int i=0; i<x; i++)
{
node *p=new node;
p->data=rand()%100;
p->next=top;
top=p;
}
return *this;
}
void show()
{
for(node *p=top; p; p=p->next)
{
cout<<p->data<<" ";
}
cout<<"\n";
}
~list()
{
node *r;
for(node *p=top; p; p=r)
{
r=p->next;
delete p;
}
}
};
int main()
{
srand(GetTickCount());
list a;
a.random().show();
return 0;
}
Your problem is that you are copying your
listbut you don’t define a copy constructor. The implicitly defined copy constructor will just copy thetoppointer so you end up attempting to delete the same chain of nodes twice.The copy occurs when you
return *this;from yourrandom()member function returning a copy of*thisby value.The shortest fix would be to make your class non-copyable by declaring a copy constructor and copy assignment operator in the private section of your class.
You can then make
randomreturnvoid, there doesn’t seem to be a good reason why it makes a copy as well.You could then just call it like this:
The longer fix would be to make your
listcopyable by making a full implementation oflist(const list&)andlist& operator=(const list&)that correctly duplicates all the nodes of the sourcelistbeing copied.