Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL vector push_back() memory double free [duplicate]

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

like image 641
Alex Avatar asked Dec 16 '22 17:12

Alex


1 Answers

You forgot to define a copy constructor and copy assignment operator, so your wrapped object is being deleted 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.

like image 194
Lightness Races in Orbit Avatar answered Jan 10 '23 03:01

Lightness Races in Orbit