Double freedom or damage when using a destructor

In the following code, when I add the line indicated by the arrow, it gives an error:

Error in `./a.out ': double freedom or corruption (fasttop): 0x00000000007a7030 * Canceled (the kernel is reset)

The code works if I do not use a 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;
}
+4
source share
2 answers

This is due to the fact that you make copies of your element when you click it in the vector, but vtx is not duplicated on the copy, so at the end of main () you will have three elements pointing to the same vtx. When the program exits, all three of them will try to delete the same int array.

+2

elm[0] vec, elm[0] vec. , , . vtx. , .

vec , . delete . .

, " " .

+2

Source: https://habr.com/ru/post/1539861/


All Articles