I am trying to write a C++ code for a minimum Heap. I want to create a vector of pointers and make sure that they are properly deleated.
I am able to create a vector of pointers, however I get an invalid conversion error from the default constructor. Why is this the case?
Also, I am trying to write a user defined destructor to ensure that I don’t have any memory issues. However, I can’t figure out why I am getting an error that the pointer was not allocated.
#include <vector>
#include <iostream>
struct A
{
A(int av, int bv):a(av),b(bv){}
int a, b;
};
struct Heap
{
Heap() : ptr(new std::vector<A*>()) {} //WHY AM I GETTING AN ERROR FOR THE DEFAULT CONSTRUCTOR AND NOT THE CONSTRUCTOR BELOW?
//ERROR: invalid conversion from ‘std::vector<A*, std::allocator<A*> >*’ to ‘long unsigned int’
//ERROR: initializing argument 1 of ‘std::vector<_Tp, _Alloc>::vector(size_t, const _Tp&, const _Alloc&) [with _Tp = A*, _Alloc = std::allocator<A*>]’
Heap(std::vector<A*> p) : ptr(p) { //Works fine.
makeHeap();
}
~Heap(){ //I DON'T UNDERSTAND WHY I AM GETTING A MEMORY ERROR HERE
std::vector<A*>::iterator it;
for(it=ptr.begin(); it<ptr.end(); ++it)
{
delete *it;
*it=NULL;
}
}//ERROR: malloc pointer being freed was not allocated
void makeHeap()
{ //some code }
std::vector<A*> ptr;
std::vector<int> heapLoc;
};
int main()
{
A a0(2,5), a1(4,2);
std::vector<A*> aArray;
aArray.push_back(&a0);
aArray.push_back(&a1);
Heap h(aArray);
return 0;
}
ptris a vector of pointers, not a pointer to a vector. So you can’t usenewto construct it on the heap and the store the address.Instead, construct it like this:
This is call the default constructor for
ptr, i.e. it will create an empty vector of pointers. You should also consider changing the name ofptrsince it is not really a pointer.Regarding your destructor (Dietmar has meanwhile posted an answer, and before him Cameron a comment, that explains it (+1 for that), but for the sake of completeness): you are getting a memory error because the pointers you store in your vector refer to addresses of objects you created on the stack. Specifically, the objects you create here:
If you want your
Heapobject to be responsible for its own objects, you should have your constructor create objects on the heap that the destructor can then delete. One way of doing this is to define the copy constructor ofHeapas follows:Your destructor can be used as-is then, but you may want to use
!=instead of<in the for-loop.Finally, I am not sure if you really need a vector of pointers (rather than a vector of objects), but if you think you do, consider using smart pointers (e.g. C++11 offers
std::unique_ptr, so you could define astd::vector<std::unique_ptr<A>>to get around many of the allocation related problems).