Reputation: 477
I had to implement a circular queue for class. The program properly Enqueues and Dequeues when I test it. But whenever I create a new object and set it equal to another, everything prints out correctly, but it crashes at the end, with an error:
Expression: _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse)
I ran the debugger and it says the problem is in a line in the Dequeue function. Here is That function.
void CQUEUE::Dequeue()
{
if(Isempty())
{
cout << "Queue is empty, nothing to delete." << endl;
return;
}
if((!Isempty()) && (front == back)) //When there is only 1 item in the queue
{ // front and back will point to the same node
delete front; //but it wont be null because of that 1 item
front = back = 0;
return;
}
qnode *p = front;
front = front -> next;
delete p;//<----------DEBUGGER POINTS HERE**************
front -> prev = back;
return;
}
Like I said, the program works fine until I create a new object and do this
CQUEUE j = k;//Any Enqueues and Dequeues after this work, but it crashes
Here is the copy constructor incase that is the problem?
CQUEUE::CQUEUE(CQUEUE & original)//Will not compile if I put Const
{ //in the parameter for some reason
front = back = 0; //So I took it out
(*this) = original;
front -> prev = back;
back -> next = front;
}
Upvotes: 1
Views: 571
Reputation: 52405
In your copy constructor you do the following:
(*this) = original;
The means that your front
pointers in CQUEUE j
and CQUEUE k
both point to the same memory.
When void CQUEUE::Dequeue()
is called for both j
and k
, delete p;
double deletes the memory, resulting in a crash.
Also, your copy constructor must be declared as const
. CQUEUE::CQUEUE(const CQUEUE& original)
. Without more code is hard to say, but in your copy constructor you need to make deep copies of the pointers (allocate memory using new
). Reading What is The Rule of Three? might help.
Upvotes: 1