I'm getting an odd error which occurs even though I am calling free(), the use is in a method called dequeue which removes elements from a priority queue, the functionality works fine but when the queue is empty the error is thrown instead of the error message which is defined.
Code and Error below:
void enqueue(string item, long time)
{
cout<<"Please Enter Entry and Time of element you wish to enqueue.."<<endl;
PRecord *tmp, *q;
tmp = new PRecord;
tmp->entry = item;
tmp->time = time;
if(front==NULL){ //if queue is empty
tmp->link = front;
front = tmp;
}
if(time<=front->time){ //if newer priority item comes through put it at front of queue
tmp->link = front;
front = tmp;
}
else {
q = front;
while (q->link != NULL && q->link->time <= time)
q=q->link;
tmp->link = q->link;
q->link = tmp;
}
}
int dequeue()
{try{
PRecord *tmp; //pointer to front of queue
if(front!=NULL){
tmp = front;
cout<<"Deleted item is: "<<endl;
displayRecord(tmp); //outputs record details
front = front->link; //link to the front
free(tmp); //dealloc memory no longer used
}
else{
cerr<<"Queue is empty - No items to dequeue!"<<endl;
}
} catch(...){
return(0);
}
}
*** glibc detected *** ./3x: double free or corruption (fasttop): 0x0000000000bb3040 ***
======= Backtrace: =========
/lib64/libc.so.6[0x35a8675dee]
/lib64/libc.so.6[0x35a8678c3d]
./3x[0x401275]
./3x[0x400f69]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x35a861ed1d]
./3x[0x400d59]
======= Memory map: ========
00400000-00402000 r-xp 00000000 08:06 2623369 /home/std/rc14lw/lab5excercisefinal/3x
00601000-00602000 rw-p 00001000 08:06 2623369 /home/std/rc14lw/lab5excercisefinal/3x
00bb3000-00bd4000 rw-p 00000000 00:00 0 [heap]
35a8200000-35a8220000 r-xp 00000000 08:01 1310722 /lib64/ld-2.12.so
When queue is empty, after adding first item you should return from enqueue
function, without it you make that front
points to itself.
Solution:
if(front==NULL)
{ //if queue is empty
tmp->link = front;
front = tmp;
return; // <-- added
}
Without return you have an issue because front
points to itself:
By these lines you create first item:
tmp = new PRecord;
tmp->entry = item;
tmp->time = time;
if(front==NULL){ //if queue is empty
tmp->link = front;
front = tmp;
}
then you check the following condition if(time<=front->time){
which returns true, it is obvious, time
are equal, then this line
tmp->link = front;
makes that front
points to itself, because tmp == front
and front
is not NULL. That is why your dequeue
function doesn't work.