我在下面的代码中实现了一个堆队列。
Queue<Heap<struct infoNode>, SIZE> queue;
for(int c = 0 ; c < SIZE; c++)
{
Heap<struct infoNode> h;
queue.enqueue(h, 0);
}
在堆中,我像这样重载了复制构造函数:
template <typename T>
Heap<T>::Heap(const Heap<T> &h)
{
cout << "this " << this << " h " << &h << endl;
capVect = h.capVect;
if(values) delete [] values;
values = new T[capVect];
dimVect = h.dimVect;
for(int i = 0; i < dimVect; i++)
values[i] = h.values[i];
}
当我制作 queue.enqueue(h, 0)
时,我得到双重释放或损坏。我不明白为什么我在这里看到相同的地址和要复制的堆。
this 0x7ffcbc2771a0 h 0x7ffcbc277190
this 0x7ffcbc2771a0 h 0x7ffcbc277190
*** Error in `./comp': double free or corruption (top): 0x00000000017f0690 ***
Aborted (core dumped)
最佳答案
在你的拷贝构造函数中
if(values) delete [] values;
因为我们在一个复制构造函数中,所以没有一个成员被初始化,除非你在成员初始化列表中指定它们。如果不是,则它们要么是默认构造的(如果它们是默认可构造的),要么是处于不确定状态(如果它们不是)。由于 value
是一个指针,它的状态是不确定的,这意味着评估它和删除它是未定义的行为。
关于c++ - 数据结构中的双重释放或损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634985/