1

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());
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • *I am stunned* -- Violation of the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). Go to the duplicate link, and go to the section marked **Managing resources**, Does that example there look familiar? – PaulMcKenzie Oct 24 '21 at 14:37
  • In modern C++, it is pretty much unnecessary to use `new` or `new[]` (I haven't directly used either in the last 10 years). Use the containers and smart pointer that manage the resources for you. – Eljay Oct 24 '21 at 14:57

1 Answers1

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335