Error in class destructor

I just started my container class and I had problems:

class Container
{
    private:

    string* BasePointer; // The starting pointer.
    unsigned int Capacity; // The number of values the container can hold.

    public:

    Container() // Default constructor.
    {
        Capacity = 1;
        BasePointer = new string[Capacity];
    }

    ~Container() // Destructor.
    {
        delete BasePointer; // Delete the container to prevent memory leaking.
    }
};

I get an error Container Classes(26467) malloc: *** error for object 0x100100088: pointer being freed was not allocated. What am I doing wrong?

+3
source share
5 answers

XXX ptr = new XXX[size]it should be compared with the version of the array delete [] ptr, and not just with the regular one delete.

Read the free C ++ store management and, as James reminds us, follow the three rules in such cases.

+7
source

you must use delete []

delete[] BasePointer;
+4
source

, new[] delete, delete delete[], . .

( ) . , , :

{
    Container c1;
    Container c2(c1);
}   // c2.~Container(); // frees the memory pointed to by 'BasePointer'
    // c1.~Container(); // also frees the memory pointed to by 'BasePointer'.

BasePointer c1, c2 , .

:

  • std::vector , . Container, , , , , .

  • boost::scoped_ptr std::unique_ptr ( ) . , , .

Container, (, , , ).

, malloc . std::allocator, .

+2

, , delete [] BasePointer;

+1

, , - new - , delete[].

new T[size], :

typedef int T[42];
int* x = new T;
delete[] x; // needs delete[] though you used new without []

, "" , , (, boost::scoped_array). , , , , op ...

0

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


All Articles