Search code examples
c++vectordynamic-memory-allocationfreecopy-constructor

Erasing object from vector causes double free


When i use vector of class B, which contains allocated memory, double free error occurs.

class B
{

public:
    std::string a;
    std::string b;
    int *hehe;

    B()
    {
        a = "Hello";
        b = ", World!";
        hehe = new int[7];
        for (int i = 0; i < 7; ++i) {
            hehe[i] = i;
        }
    }

    ~B() {
        if (hehe)
            delete[] hehe;
    }
};
std::vector<class B> a(5);
    a.erase(a.begin() + 2);

Error message:

a.out(46830,0x10e0015c0) malloc: *** error for object 0x7ff12dc02a80: pointer being freed was not allocated a.out(46830,0x10e0015c0) malloc: *** set a breakpoint in malloc_error_break to debug

And this code is working fine. I am stunned.

std::vector<class B> a(1);
a.erase(a.begin());

Solution

  • You did not define the copy constructor or move constructor. So the same value of the pointer hehe is copied from one object to another object and the destructor frees the memory pointed to by the pointer hehe more than one time due to storing the same value of hehe in more than one object.

    For example the copy constructor could be defined the following way

    B( const B &b ) : a( b.a ), b( b.b ), hehe( new int[7] )
    {
        for (int i = 0; i < 7; ++i) {
            hehe[i] = b.hehe[i];
        }
    }
    

    Also you need to define explicitly the copy assignment operator.