I have a class that looks like this :
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
vector<int*> V;
public:
MyClass();
MyClass(int n);
~MyClass();
};
MyClass::MyClass()
{
return;
}
MyClass::MyClass(int n)
{
int* T = new int[n];
for(int i=0; i<n; i++)
{
T[i]=i;
V.push_back(&(T[i]));
}
return;
}
MyClass::~MyClass()
{
for(int i =0; i<V.size(); i++)
delete V[i];
return;
}
int main()
{
MyClass C(5);
return 0;
}
- What’s wrong about my destructor? I get a “* glibc detected * ./a.out: free(): invalid pointer:…” error upon execution of this.
- Do you think I should use ptr_vector? I don’t know if I have the courage to learn about those.
Thanks in advance!
In your destructor, you’re deleting pointers that were never allocated. You can only use
delete(ordelete[]) if there’s a specific matching use ofnew(ornew[]), and for n-1 of yourintpointers, there is no such call.If you want your vector to hold pointers to individual unrelated
ints, then you need to usenewto allocate each one individually. If they’re always going to be in an array like this, then keep a pointer to that array in a member, and delete just that one pointer in your destructor.