Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double free or corruption when using destructor [duplicate]

In the following code when I add the the line which is specified with an arrow gives error:

Error in `./a.out': double free or corruption (fasttop): 0x00000000007a7030 * Aborted (core dumped)

The code works if I do not use destructor. Any idea?

#include<iostream>
#include<vector>

struct Element
{
    int *vtx;

    ~Element ()
    {
        delete [] vtx;
    }
};

int main ()
{
    Element *elm = new Element [2];
    elm[0].vtx = new int [2]; // <----- adding this gives error

    std::vector <Element> vec;
    vec.push_back (elm[0]);
    vec.push_back (elm[0]);

    return 0;
}
like image 802
Shibli Avatar asked May 09 '14 05:05

Shibli


1 Answers

When you add elm[0] to vec, copies of elm[0] are stored in vec. Since you haven't defined a copy constructor, the compiler used the default one -- which performs a member by member copy. In this case, it keeps a copy of the pointer vtx. Now you have three objects pointing to the same memory.

When vec gets destructed, it calls the destructor on two of those objects. They each try delete on the same pointer. Hence the error.

If you want to avoid errors like these, check out Rule of Three.

like image 115
R Sahu Avatar answered Sep 21 '22 15:09

R Sahu