De-allocation problems when stacking container onto container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

template <class T>
class Container {
private:
    T* myList;
    size_t length;
public:
    Container() : myList(nullptr), length(0) {}
    Container(initializer_list<T> argList) {
        length = argList.size();
        myList = new T[length]();
        
        size_t i = 0;
        for(const T& item : argList) {
            if(i == length)
                return;
            myList[i] = item;
            i++;
        }
    }
    ~Container() {
        delete[] myList;
    }
};

int main(int argc, const char * argv[]) {
    Container<Container<int>> c = {{1,2}, {3,4}};
    return 0;
}


Running this code gives the following error:
1
2
3
pl(9524,0x100391380) malloc: *** error for object 0x100525760: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Program ended with exit code: 9


The structure looks okay to me, but apparently I'm missing something.
You didn't follow the rule of three.
https://en.cppreference.com/w/cpp/language/rule_of_three
Thanks for telling me why the rule of three is important.
I had to implement the copy assignment operator to make the functionality complete and correct.
Topic archived. No new replies allowed.