Possible Duplicate:
What is The Rule of Three?
I have the a problem of the double freeing of memory in the following program.
The debugger shows that the issue is in the push_back()
function.
Class A:
class A {
public:
A(int x);
int x;
};
A::A(int x) {
this->x = x;
}
Class B:
class B {
public:
B(int x);
~B();
A* a;
};
B::B(int x) {
this->a = new A(x);
}
B::~B() {
delete a;
}
Main function:
int main() {
vector<B> vec;
for(int i = 0; i < 10; i++) {
vec.push_back(B(i)); <------------ Issue is here
}
cout << "adding complete" << endl;
for(int i = 0; i < 10; i++) {
cout << "x = " << (vec[i].a)->x << endl;
}
return 0;
}
What is wrong in this code?
EDIT: Error double free or memory corruption
You forgot to define a copy constructor and copy assignment operator, so your wrapped object is being delete
d by some B
.... then again when some copy of B
goes out of scope.
In this case it's the B(i)
temporary on the line you've identified, as well as an implementation-defined number of copies within the vector.
Abide by the rule of three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With