【发布时间】:2018-10-26 06:05:50
【问题描述】:
我得到一个奇怪的错误,即使我正在调用 free(),它的使用是在一个名为 dequeue 的方法中,它从优先级队列中删除元素,该功能工作正常,但是当队列为空时,错误是抛出而不是定义的错误消息。
以下代码和错误:
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
【问题讨论】:
-
为什么不赞成?该问题具有所有要求,并且清晰简洁。
-
您是如何分配和初始化您的预记录的?你有正当理由选择 malloc/free 而不是 new/delete 吗?
-
添加了我的 enqueue 方法来显示 PRecords 的分配,当我使用 delete 时会有同样的行为
-
无论如何,您使用
new创建一个对象,然后使用free解除分配。这是未定义的行为(它不会调用析构函数~PRecord())。请改用delete tmp;。 -
@rahulchawla 现在有一些有趣的答案。但无论如何,c++ 不是 c。所以 new/delete 或 new[]/delete[] 忘记 malloc()/free()。
标签: c++ memory-management queue malloc free