I'm trying to use in my implementation the fibonacci heap from boost but my program crashes, when I calling decrease function, this the example (W is a simple class):
struct heap_data
{
boost::heap::fibonacci_heap<heap_data>::handle_type handle;
W* payload;
heap_data(W* w)
{
payload = w;
}
bool operator<(heap_data const & rhs) const
{
return payload->get_key() < rhs.payload->get_key();
}
};
int main()
{
boost::heap::fibonacci_heap<heap_data> heap;
vector<heap_data> A;
for (int i = 0; i < 10; i++)
{
W* w = new W(i, i + 3);
heap_data f(w);
A.push_back(f);
boost::heap::fibonacci_heap<heap_data>::handle_type handle = heap.push(f);
(*handle).handle = handle; // store handle in node
}
A[5].payload->decr();
heap.decrease(A[5].handle);
return 0;
}
The problem is quite trivial.
You have two containers (vector
A
and heapheap
).The heap contains copies of the data in the vector:
You set the handle only on the copy in the heap:
Hence, in the temporary
f
and the vectorA
's elements, the value ofhandle
is indeterminate (you just didn't give it any value).Therefore when you do
you invoke Undefined Behaviour because you depend on the value of
A[5].handle
, which is uninitialized.Simpler, correct, example:
Live On Coliru