1

I have the following code:

struct Matrix {
    int * data;

    Matrix(int sz) {
        std::cout << this << " constructed" << std::endl;
        data = new int[sz];
        for (int i = 0; i < sz; i++) {
            data[i] = sz;
        }
    }
    ~Matrix() {
        std::cout << this << " destructed" << std::endl;
        delete[] data;
    }
};

int main()
{
    std::vector<Matrix> my_matrices;
    for (int i = 1; i < 3; i++) {
        std::cout << my_matrices.capacity() << std::endl;
        my_matrices.emplace_back(i);
    }
}

This compiles, but gives the following error when I try to run it:

0
0x5642c4882eb0 constructed
1
0x5642c4883308 constructed
0x5642c4882eb0 destructed
2
0x5642c4883350 constructed
0x5642c4883300 destructed
free(): double free detected in tcache 2
Aborted (core dumped)

If I understand it correctly the destructor is called to destruct a memory adress that does not contain a Matrix-object. How is this possible/what am I doing wrong?

I have noticed that it does work when I try to do it like this:

int main()
{
    std::vector<Matrix*> my_matrices;
    for (int i = 1; i < 3; i++) {
        std::cout << my_matrices.capacity() << std::endl;
        my_matrices.emplace_back(new Matrix(i));
    }
    for (int i = 1; i < 3; i++) {
        delete my_matrices[i];
    }
}

But this seems complicated and does not make me understand why the first example did not work. I am not entirely sure whether this causes a memory leak or not.

east1000
  • 1,240
  • 1
  • 10
  • 30
Squaloto
  • 11
  • 1
  • 1
    Does this answer your question? [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Richard Critten Sep 01 '21 at 07:04

0 Answers0